boost中的condition_variable (条件变量)的使用

代码基本来自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 char* str)
{
	boost::mutex::scoped_lock lock(mut);  
	cout<<__FUNCTION__<<str<<endl;
	retrieve_data(str);
	prepare_data(str);
	{
//		boost::lock_guard<boost::mutex> lock(mut); // 使用公共资源data_ready前先lock互斥体
		data_ready = true;
	}
/*	cond.notify_one();*/ // 唤醒等待条件变量的一个线程:即调用cond.wait()的线程; mut在wait_for_data_to_process()中的将被重新锁定
	cond.notify_all(); // 唤醒等待条件变量的多个线程
}

int _tmain(int argc, _TCHAR* argv[])
{
	boost::thread thr1(wait_for_data_to_process, "(); // thread1");
	boost::thread thr2(wait_for_data_to_process, "(); // thread2");
	boost::thread thr3(prepare_data_for_processing, "(); // thread3"); // 没有此行,线程1,2总是处在wait

	// 三线程各执行一遍,但顺序不定
	thr1.join();
	thr2.join();
/*	thr3.join();*/ // 没有必要

	return 0;
}
再给个链接:http://cpp.ezbty.org//myfiles/boost/doc/html/thread/synchronization.html



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章