代码基本来自boost手册,进行了稍微的修改和备注
#include <boost\thread.hpp>
#include <iostream>
using std::cout;
using std::endl;
boost::condition_variable cond; // 条件变量
boost::mutex mut; // 互斥量,使用他来进行线程同步
bool data_ready; // 公共对象
void process_data(const char* str)
{
cout<<__FUNCTION__<<str<<endl;
}
void wait_for_data_to_process(const char* str)
{
boost::unique_lock<boost::mutex> lock(mut);
cout<<__FUNCTION__<<str<<endl;
while(!data_ready)
{
// lock 对象会传递给 wait函数: wait 函数会自动将线程添加到等待条件变量的线程集合中,
// 并且解锁传递进来的互斥量,允许其他线程申请。
// 这样允许其他线程获取互斥量来更新共享的数据,确保条件变量关联的数据被正确同步。
// 当线程被唤醒,函数退出前互斥量会再次被锁定
cond.wait(lock);
}
process_data(str);
}
void retrieve_data(const char* str) // 回收数据
{
cout<<__FUNCTION__<<str<<endl;
}
void prepare_data(const char* str)
{
cout<<__FUNCTION__<<str<<endl;
}
void prepare_data_for_processing(const c