boost::condition_variable 用法:
當線程間的共享數據發生變化的時候,可以通過condition_variable來通知其他的線程。消費者wait 直到生產者通知其狀態發生改變,Condition_variable是使用方法如下:
·當持有鎖之后,線程調用wait
·wait解開持有的互斥鎖(mutex),阻塞本線程,並將自己加入到喚醒隊列中
·當收到通知(notification),該線程從阻塞中恢復,並加入互斥鎖隊列(mutex queue)
線程被喚醒之后繼續持有鎖運行。
以下一個例子轉自:
template<typename Data>
class concurrent_queue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
};
