問題:有一個生產者,多個消費者,生產者每生產一個,放入隊列,多個消費者順序從隊列中取出數據,打印最終結果。
分析:首先這題,我本意應該設計成如下模型:生產者單開一個線程,向隊列中放入數據,而消費者在鎖的保護下,從隊列中去數據。但是在實際編程中,發現在隊列只有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(); }