[英]Using condition variable in a producer-consumer situation
我正在嘗試了解條件變量以及如何在生產者 - 消費者情況下使用它。 我有一個隊列,其中一個線程將數字推入隊列,而另一個線程從隊列中彈出數字。 我希望在生產線程放置一些數據時使用條件變量來指示消費線程。 問題是有時(或大多數時候)它只將兩個項目推入隊列然后掛起。 我在produce()函數中指出它在調試模式下運行時停止。 任何人都可以幫我指出為什么會這樣嗎?
我有以下全局變量:
boost::mutex mutexQ; // mutex protecting the queue
boost::mutex mutexCond; // mutex for the condition variable
boost::condition_variable condQ;
以下是我的消費者主題:
void consume()
{
while( !bStop ) // globally declared, stops when ESC key is pressed
{
boost::unique_lock lock( mutexCond );
while( !bDataReady )
{
condQ.wait( lock );
}
// Process data
if( !messageQ.empty() )
{
boost::mutex::scoped_lock lock( mutexQ );
string s = messageQ.front();
messageQ.pop();
}
}
}
下面是我的制作人主題:
void produce()
{
int i = 0;
while(( !bStop ) && ( i < MESSAGE )) // MESSAGE currently set to 10
{
stringstream out;
out << i;
string s = out.str();
boost::mutex::scoped_lock lock( mutexQ );
messageQ.push( s );
i++;
{
boost::lock_guard lock( mutexCond ); // HANGS here
bDataReady = true;
}
condQ.notify_one();
}
}
在條件變量中使用時,必須使用相同的互斥鎖來保護隊列。
這應該是你所需要的:
void consume()
{
while( !bStop )
{
boost::scoped_lock lock( mutexQ);
// Process data
while( messageQ.empty() ) // while - to guard agains spurious wakeups
{
condQ.wait( lock );
}
string s = messageQ.front();
messageQ.pop();
}
}
void produce()
{
int i = 0;
while(( !bStop ) && ( i < MESSAGE ))
{
stringstream out;
out << i;
string s = out.str();
boost::mutex::scoped_lock lock( mutexQ );
messageQ.push( s );
i++;
condQ.notify_one();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.