如何在C ++ 11中实现有关并发的脚本

时间:2019-01-03 04:52:26

标签: c++11

我在c ++ 11中实现了多线程并发脚本。但是我坚持了。

int product_val = 0;
-线程1:将product_val增加到线程2中的向量,通知线程2并等待线程2打印product_val;
-线程2:等待并减少product_val,打印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 }

0 个答案:

没有答案