zoukankan      html  css  js  c++  java
  • c++并发练习---生产者消费者模型

    问题:有一个生产者,多个消费者,生产者每生产一个,放入队列,多个消费者顺序从队列中取出数据,打印最终结果。

    分析:首先这题,我本意应该设计成如下模型:生产者单开一个线程,向队列中放入数据,而消费者在锁的保护下,从队列中去数据。但是在实际编程中,发现在队列只有100个数的情况,线程不切换,当队列数据多的时候,会发生切换,但是也不是我所想象的那种随机切换,思考至今,也没有一个合理的解释/(ㄒoㄒ)/~~。最后我把题目改成了生产者没生产一个数据,就通知消费者去取,这样保证了一定的同步,但是估计或许开销会大一些。。。

    如果大家有什么好的方法或者解释,请联系我,谢谢

    #include<iostream>
    #include<thread>
    #include<mutex>;
    #include<condition_variable>
    #include<queue>
    #include<vector>
    std::mutex mut;
    std::condition_variable empty, full;
    std::queue<int> Q;
    int flag;
    bool over = false;
    
    void conduct(int num, int count)
    {
    	for (int i = 0; i < num; i++)
    	{
    		std::unique_lock<std::mutex> lk(mut);
    		empty.wait(lk);
    		Q.push(i);
    		flag = i % count;
    		full.notify_all();
    		lk.unlock();
    	}
    	over = true;
    }
    void consumer(int id, int count)
    {
    	while (true)
    	{
    		std::unique_lock<std::mutex> lk(mut);
    		full.wait(lk, [&]() {return flag == id; });
    
    		if (!Q.empty())
    		{
    			int i = Q.front();
    			Q.pop();
    			std::cout << "thread " << id << " get " << i << std::endl;
    		}
    
    		if (over)
    			break;
    		empty.notify_one();
    	}
    
    	flag = (id==count-1?0:id+1);
    	full.notify_all();
    }
    
    int main()
    {
    	int count;
    	int num;
    	std::vector<std::thread> threads;
    	std::cout << "请输入需要生产的数量" << std::endl;
    	std::cin >> num;
    	std::cout << "请输入同时进行的线程数:" << std::endl;
    	std::cin >> count;
    	std::thread t1(conduct, num, count);
    	for (int i = 0; i < count; i++)
    		threads.push_back(std::thread(consumer, i, count));
    
    	t1.join();
    	for (auto &t : threads)
    		t.join();
    }
    

      

  • 相关阅读:
    图的深度优先遍历(邻接表,递归,非递归)
    图的深度优先遍历(邻接矩阵,递归,非递归)
    【转】C语言邻接表的实现
    图的存储
    堆排序_C实现
    快排_C实现
    交换二叉树中所有结点的左右子树的位置
    二叉树层次遍历_判断结点所属层次
    二叉树_非递归先中后序_递归非递归求深度
    二叉树非递归遍历(前、中、后)
  • 原文地址:https://www.cnblogs.com/break-python/p/5557438.html
Copyright © 2011-2022 走看看