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



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