C++-BOOST(1)-線程(Thread)與互斥量(mutex)

1.線程調用兩種方式:函數與類

using namespace boost;
//1.函數調用
//2.類調用
void fun()
{
	cout << "fun Hello world, I''m a fun thread!" << endl;
}
class myClassThread
{
  public:
	void fun()    //被調用的函數
	{
		cout <<	"Hello world, I''m a myClassThread!"<<endl;
	}
	void start()  //啓動線程函數
	{
		boost::function0< void> f = boost::bind(&myClassThread::fun, this);
		boost::thread thrd(f);
		thrd.join();
	}

};

void myThread_main()
{
	cout << "myThread_main" << endl;
	
	boost::thread thrd(&fun);   //1.調用函數線程
	thrd.join();

	cout << " myClassThread" << endl;//2.調用類線程
	myClassThread m_thread;
	m_thread.start();
}


2.互斥量:2.1mutex  會阻塞線程 單獨用時要try catch
                  2.2timed_mutex 超時立即返回
                  2.3 lock_guard 自動完成mutex鎖定解鎖操作
 

void myThread_main()
{
	
	//互斥變量,
	//1.1 mutex 但是會阻塞線程 單獨用時要try catch
	boost::mutex mu;   
	try {
		mu.lock();                  //鎖定互斥量
		cout<<"操作共享資源"<<endl; //操作共享資源
		mu.unlock();                //解鎖互斥量

	}
	catch (...)
	{
		mu.unlock();
	}

	//1.2 timed_mutex 超時立即返回
	boost::timed_mutex tmu;
	auto flag = tmu.try_lock_for(100_ms);//等待100ms
	if (flag)
	{
		cout<<"lock timed_mutex"<<endl;//訪問共享資源
		tmu.unlock();
	}
	//哪怕未獲得解鎖,也執行其他操作

	 //1.3 lock_guard 自動完成mutex鎖定解鎖操作
	 //1.3.1 與mutex同用
	boost::mutex mu2;                         //聲明互斥量對象
	boost::lock_guard<boost::mutex> g(mu2);   //使用lock_guard
	cout<<"some operation"<<endl;             //訪問共享資源


	//3.3.2 與timed_mutex同用
	boost::timed_mutex tmu2;                  //定義互斥量
	auto flag = tmu2.try_lock_for(100_ms);     //鎖定時間爲100ms
	if (flag)
	{
	                    //定義互斥量
		boost::lock_guard< boost::timed_mutex> g(tmu2, boost::adopt_lock);//不會再次加鎖
		cout << "lock timed_mutex" << endl;                             //訪問共享資源
		
	}
	                                                  //自動釋放




}

 

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