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

two_pthreads.cpp (1317B)


      1 #include <cassert>
      2 #include <iostream>
      3 #include <pthread.h>
      4 
      5 // DISCLAIMER: this code contains a race condition.
      6 
      7 // global barrier
      8 pthread_barrier_t barrier;
      9 
     10 // shared variables
     11 int A = 0;
     12 int B = 0;
     13 
     14 // work done by the threads
     15 void *worker(void *t)
     16 {
     17     long tid = (long)t;
     18 
     19     if (0 == tid) {
     20         A = 1;
     21         // pthread_barrier_wait(&barrier);
     22         const int x = B; // thread local variable
     23         std::cout << "Thread 0: x = " << x << std::endl;
     24     } else if (1 == tid) {
     25         B = 1;
     26         // pthread_barrier_wait(&barrier);
     27         const int y = A; // thread local variable
     28         std::cout << "Thread 1: y = " << y << std::endl;
     29     }
     30 
     31     return nullptr;
     32 }
     33 
     34 int main(void)
     35 {
     36     // we use two threads
     37     constexpr int nthreads = 2;
     38 
     39     // allocate thread array
     40     pthread_t threads[nthreads];
     41 
     42     // initialize barrier
     43     int s = pthread_barrier_init(&barrier, nullptr, nthreads);
     44     assert(s == 0);
     45 
     46     // fork
     47     for (long i = 0; i < nthreads; ++i) {
     48         s = pthread_create(&threads[i], nullptr, worker, (void *)i);
     49         assert(s == 0);
     50     }
     51 
     52     // join
     53     for (int i = 0; i < nthreads; ++i) {
     54         s = pthread_join(threads[i], nullptr);
     55         assert(s == 0);
     56     }
     57 
     58     // clean up
     59     s = pthread_barrier_destroy(&barrier);
     60     assert(s == 0);
     61 
     62     return 0;
     63 }