生产-消费者,C++11实现

C++11中新增加了线程库<thread>和原子操作库<atomic>,使用这两个库可以实现生产——消费者模型。上代码

 1 //生产者生产函数
 2 void product(std::atomic<unsigned> &i)
 3 {
 4     while (true)
 5     {
 6         if (i < 10)
 7         {
 8             Sleep(500);
 9             std::cout << "I make a fucker!" << std::endl;
10             ++i;
11             return;
12         }
13     }
14 }
15 //消费者消费函数
16 void consumer(std::atomic<unsigned>& i)
17 {
18     while (true)
19     {
20         if (i > 0)
21         {
22             --i;
23             std::cout << "I kill a fucker!" << std::endl;
24             Sleep(200);
25 
26         }
27     }
28 }
29 //生产者线程函数
30 void testP(std::atomic<unsigned> &i)
31 {
32 
33     while (true)
34     {
35         product(i);
36     }
37 }
38 //消费者线程函数
39 void testC(std::atomic<unsigned> &i)
40 {
41 
42     while (true)
43     {
44         consumer(i);
45     }
46 }
47 
48 int main()
49 {
50     std::atomic<unsigned> i = 0;
51     std::thread trPro(testP , std::ref(i)), trSel(testC, std::ref(i));
52     trPro.detach();
53     trSel.detach();
54 
55     return 0;
56 }

 

 
运行结果截图,看来暂时没问题

 

由于没有看过什么书,这都是我瞎猜的…

posted @ 2019-07-28 19:51  Hyapp  阅读(238)  评论(0编辑  收藏  举报