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_critical.cpp (871B)


      1 #include <iostream>
      2 #include <omp.h>
      3 #include <unistd.h>
      4 
      5 int main(void)
      6 {
      7     int a = 0;
      8     int b = 0;
      9     // benchmark execution time of parallel region
     10     const double t0 = omp_get_wtime();
     11 #pragma omp parallel
     12     {
     13         const int tid = omp_get_thread_num();
     14 #ifdef TWO_CRITICAL
     15 #pragma omp critical(critical_a)
     16 #else
     17 #pragma omp critical
     18 #endif /* TWO_CRITICAL */
     19         {
     20             a += tid;
     21             usleep(50000);
     22         }
     23 #ifdef TWO_CRITICAL
     24 #pragma omp critical(critical_b)
     25 #else
     26 #pragma omp critical
     27 #endif /* TWO_CRITICAL */
     28         {
     29             // if the operation would involve a read or write from/to `a`, then
     30             // this would be a race condition
     31             b += tid;
     32             usleep(50000);
     33         }
     34     }
     35     const double dt = omp_get_wtime() - t0;
     36     std::cout << "Elapsed time: " << dt << " seconds\n";
     37     return a + b;
     38 }