two_ompthreads.cpp (838B)
1 #include <iostream> 2 #include <omp.h> 3 4 // DISCLAIMER: this code contains a race condition. Beware of false positives 5 // from the thread sanitizer due to the OpenMP runtime, which TSan 6 // has a hard time to understand. See the pthreads version for the 7 // proof. 8 int main(void) 9 { 10 // shared variables 11 int A = 0; 12 int B = 0; 13 14 #pragma omp parallel num_threads(2) // use 2 threads 15 { 16 const int tid = omp_get_thread_num(); // my ID 17 if (0 == tid) { 18 A = 1; 19 const int x = B; // thread local variable 20 std::cout << "Thread 0: x = " << x << std::endl; 21 } else if (1 == tid) { 22 B = 1; 23 const int y = A; // thread local variable 24 std::cout << "Thread 1: y = " << y << std::endl; 25 } 26 } 27 return 0; 28 }