阿里面试:生产者消费者模型

阿里内推二面编程题:实现一个生成者消费者模型

要求:
1、多线程生产者、多线程消费者
2、当队列超过>100时,生产者停止生产,队列<20,消费者停止消费
3、适当加一些print来验证你的程序,不然整个程序跑起来,你是不知道程序是什么情况的

 1 /* Hello World program */
 2 
 3 #include <iostream>
 4 
 5 #include <queue>
 6 #include <mutex>
 7 #include <condition_variable>
 8 #include <thread>
 9 #include <functional>
10 
11 //几个要求
12 //1、多线程生产者、多线程消费者
13 //2、当队列超过>100时,生产者停止生产,队列<20,消费者停止消费
14 //3、适当加一些print来验证你的程序,不然整个程序跑起来,你是不知道程序是什么情况的
15 
16 
17 std::queue<int> q;
18 std::mutex m;
19 std::condition_variable cv1; //for 100;
20 std::condition_variable cv2; //for 20;
21 
22 void produce(int x){
23     std::unique_lock<std::mutex> lck(m);
24     //cycle check.
25     while(q.size()>100){
26         cv1.wait(lck);
27     }
28     q.push(x);
29     std::cout << "produce:" << x << std::endl;
30     if(q.size()>=20) cv2.notify_all();
31 }
32 
33 void consume(){
34     std::unique_lock<std::mutex> lck(m);
35     while(q.size()<20) cv2.wait(lck);
36 
37     std::cout << "consume:" << q.front() << std::endl;
38     q.pop();
39     if(q.size()<100) cv1.notify_all();
40 }
41 
42 
43 int main()
44 {
45     std::thread producers[200];
46     for(int i=0;i<200;i++){
47         producers[i]=std::thread(produce,i);
48     }
49 
50     std::thread consumers[200];
51     for(int i=0;i<200;i++){
52         consumers[i] = std::thread(consume);
53     }
54 
55     for(auto& p : producers){
56         p.join();
57     }
58     for(auto& c : consumers){
59         c.join();
60     }
61 
62     //std::cout << "Hello World!";
63     return 0;
64 }

 

posted @ 2017-08-10 15:54  wxquare  阅读(1404)  评论(0编辑  收藏  举报