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();
}
}; |