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

scenario_1_3.cpp (1215B)


      1 #include <iostream>
      2 #include <omp.h>
      3 #include <random>
      4 #include <unistd.h>
      5 
      6 // shared variables
      7 int A = 0;
      8 int B = 0;
      9 
     10 void task1()
     11 {
     12     A = 1;
     13     const int x = B;
     14     std::cout << "Thread 0: x = " << x << std::endl;
     15 }
     16 
     17 void task2()
     18 {
     19     B = 1;
     20     const int y = A;
     21     std::cout << "Thread 1: y = " << y << std::endl;
     22 }
     23 
     24 int main(void)
     25 {
     26 #pragma omp parallel num_threads(2) // use 2 threads
     27     {
     28         // generate some randomness to simulate load imbalance
     29         std::random_device rd;
     30         std::mt19937 rng(rd());
     31         std::uniform_int_distribution<int> uniform(10, 50);
     32         usleep(uniform(rng));
     33 
     34         const int tid = omp_get_thread_num(); // my ID
     35 
     36         // the following pragma necessarily serializes the code -> sequential
     37         // consistency (synchronization primitive)
     38 #pragma omp critical
     39         {
     40             // This code must be in a critical section because task1 and task2
     41             // read and write from/to shared memory.  Depending on which thread
     42             // acquires the lock first, you will either get scenario 1 or 3:
     43             if (0 == tid) {
     44                 task1();
     45             } else {
     46                 task2();
     47             }
     48         }
     49     }
     50     return 0;
     51 }