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_region.cpp (1643B)


      1 // vim: foldmethod=marker
      2 #include <iostream>
      3 #include <omp.h>
      4 
      5 void declare_static(void)
      6 {
      7     const int tid = omp_get_thread_num(); // reference
      8 
      9     // declared_in_region is shared among threads who call this function.
     10     // NOTE: the assignment here is not a race condition -> the compiler
     11     // initializes this variable at compile time, not the threads at runtime!
     12     static int declared_in_region = 1234567890;
     13     //
     14     // PROOF: see assembly code
     15     // all threads print the initial value of declared_in_region {{{1
     16 #pragma omp single // write header line (only one needed)
     17     {
     18         std::cout << "Initial value of declared_in_region:\n";
     19     } // implicit barrier here
     20 #pragma omp critical // all threads must write this
     21     {
     22         std::cout << "\ttid " << tid << ":\t" << declared_in_region << '\n';
     23     } // NO implicit barrier here!
     24     // we must synchronize here, otherwise a thread might continue while others
     25     // still need to print the std::cout line above.  Test it by commenting out
     26     // the barrier.
     27 #pragma omp barrier
     28     // 1}}}
     29 
     30     // DISCLAIMER: the next commented line would be a race condition!
     31     // declared_in_region = tid;
     32     //
     33     // PROOF: declared_in_region is shared
     34 #pragma omp single
     35     {
     36         declared_in_region = tid;
     37     } // others wait here
     38 #pragma omp single nowait
     39     {
     40         std::cout << "I am tid " << tid
     41                   << " and `declared_in_region` has been written to by tid "
     42                   << declared_in_region << '\n';
     43     }
     44 }
     45 
     46 int main(void)
     47 {
     48 #pragma omp parallel
     49     {
     50         declare_static(); // all threads call this function
     51     }
     52 
     53     return 0;
     54 }