[英]Producer and Consumer Problem waiting threads
I tried to code Producer and Consumer Problem but after producing up to a certain value -(val) produce thread ends.我尝试编写生产者和消费者问题的代码,但在产生一定值后 -(val) 产生线程结束。 but the consumer thread's condition variable waiting for notification but there is no thread to notify so my program does not end.
但是消费者线程的条件变量等待通知但是没有线程通知所以我的程序没有结束。 What changes should I made?
我应该做哪些改变?
#include<bits/stdc++.h>
using namespace std;
mutex m;
vector<int>buffer;
condition_variable cv;
void producer(int val){
while(val){
std::unique_lock<mutex>lock(m);
cv.wait(lock, []{ return buffer.size()<50; });
buffer.push_back(val--);
cout<<"Produced : "<<buffer.back()<<endl;
lock.unlock();
cv.notify_one();
}
}
void consumer(){
while(1){
std::unique_lock<mutex>lock(m);
cv.wait(lock, []{return buffer.size() > 0 ; });
cout<<"Consumed : "<<buffer.back()<<endl;
buffer.pop_back();
lock.unlock();
cv.notify_one();
}
}
int main()
{
int attempt=1;
thread t1(producer,30);
thread t2(consumer);
t1.join();
t2.join();
return 0;
}
You need to have another variable which will indicate that your producer will produce no more so your consumer will know that你需要有另一个变量来表明你的生产者将不再生产,这样你的消费者就会知道
So the minimum modification of your code might look as follows:因此,您的代码的最小修改可能如下所示:
using namespace std;
mutex m;
vector<int>buffer;
condition_variable cv;
bool producerExhausted = false;
void producer(int val){
while(val){
std::unique_lock<mutex>lock(m);
cv.wait(lock, []{ return buffer.size()<50; });
buffer.push_back(val--);
cout<<"Produced : "<<buffer.back()<<endl;
producerExhausted = val == 0;
lock.unlock();
cv.notify_one();
}
}
void consumer(){
while(1){
std::unique_lock<mutex>lock(m);
if(!producerExhausted)
cv.wait(lock, []{return buffer.size() > 0 ; });
cout<<"Consumed : "<<buffer.back()<<endl;
buffer.pop_back();
if(producerExhausted && buffer.empty())
break;
lock.unlock();
cv.notify_one();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.