mercredi 2 janvier 2019

How to implement this script about concurrency in c++ 11

I implement an concurrency script of multi thread in c++ 11 . But i stuck .

int product_val = 0;
- thread 1 : increase product_val to vector in thread 2 , notify thread 2 and waiting for thread 2 print product_val;
- thread 2 : wait and decrease product_val , print product_val

1 #include <iostream>
2 #include <thread>
3 #include <condition_variable>
4 #include <mutex>
5 #include <chrono>
6 #include <queue>

7 using namespace std;

8 int product_val = 0; 
9 std::condition_variable cond;
10 std::mutex sync;
11 int main() {
12      //thread 2    
13  std::thread con = std::thread([&](){
14      while (1)
15      {           
16          std::unique_lock<std::mutex> l(sync);
17          cond.wait(l);
18          product_val--;
19          printf("Consumer product_val = %d \n", product_val);
20          l.unlock();
21      }
22  });
23      //thread 1 (main thread)  process 
24  for (int i = 0; i < 5; i++)
25  {
26      std::unique_lock<std::mutex> l(sync);
27      product_val++;
28      std::cout << "producer product val " << product_val;
29      cond.notify_one();      
30      l.unlock();

31      l.lock();
32      while (product_val)
33      {
34              
35      }
36              std::cout << "producer product val " << product_val;  
37      l.unlock();
38  }
39  return 0;
40 }

Aucun commentaire:

Enregistrer un commentaire