cs205-lecture-examples

Example codes used during Harvard CS205 lectures
git clone https://git.0xfab.ch/cs205-lecture-examples.git
Log | Files | Refs | README | LICENSE

omp_threadprivate.cpp (696B)


      1 #include <iostream>
      2 #include <omp.h>
      3 
      4 // static (global) in compilation unit (shared by default)
      5 static int global = -1;
      6 
      7 // predetermine `global` as thread private (has to be done before first use).
      8 // Without this pragma global will be shared
      9 #pragma omp threadprivate(global)
     10 
     11 void access_global(void)
     12 {
     13     const int tid = omp_get_thread_num(); // reference
     14 
     15     // DISCLAIMER: this may be a race condition, depending on threadprivate
     16     // above!
     17     global = tid;
     18 
     19 #pragma omp critical // all threads must write this
     20     {
     21         std::cout << "\ttid " << tid << ":\t" << global << '\n';
     22     }
     23 }
     24 
     25 int main(void)
     26 {
     27 #pragma omp parallel
     28     {
     29         access_global();
     30     }
     31 
     32     return 0;
     33 }