boost庫使用—線程類

boost庫使用—線程類


boost 庫中提供了兩種創建線程的方式,一種是單個線程創建,另外一種是線程組的創建,進行線程管理

;同時,在線程庫中還提供了鎖的方式;


thread 線程

thread 就是沒有組管理,與我們在linux下使用pthread_create()函數是一樣的,只是在C++11中,引入了boost中的thread方法;


包含頭文件:

#include <boost/thread.hpp>

using namespace boost;


常用方法:

  • thread th(…) 創建線程

  • th.interrupt() 中斷線程

  • th.get_id() 獲取線程ID

  • th.join() 等待線程結束


案例:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>

using namespace std;

boost::mutex io_mutex;

void Print(int x, string str)
try
{
	for (int i = 0; i < x; i++)
	{
		boost::mutex::scoped_lock lock(io_mutex);
		cout << "str:"<<str << endl;
	}
}
catch (boost::thread_interrupted&)
{
	cout << "thread is interrupt" << endl;
}

int main()
{
	int x = 5;
	boost::thread th1(Print,ref(x),"hello boost");
	boost::thread th2(Print,ref(x),"hello thread");
	//綁定bind函數function
	boost::function<void()>F(bind(Print, ref(x), "hello bind"));
	boost::thread th3(F);
	//中斷線程
	th3.interrupt();
	//獲取線程ID
	cout << "th3_id:"<<th3.get_id() << endl;
	//睡眠2s
	boost::this_thread::sleep(boost::posix_time::seconds(2));

	//等待線程結束
	th1.join();
	th3.join();
	//超過3s結束線程
	th2.timed_join(boost::posix_time::seconds(3));
	system("pause");
	return 0;
}



線程組 thread_group

線程組很類似線程池,對線程進行管理;內部使用的是boost::thread。


包含頭文件:

#include <boost/thread.hpp>

using namespace boost;


常用方法:

boost::thread_group gt;

  • gt.create_thread 創建線程
  • gt.add_thread();增加線程
  • gt.remove_thread() 移除線程
  • gt.join_all() 等待線程結束

案例:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <boost/bind.hpp>

using namespace std;

boost::mutex io_mutex;

void Print(int x, string str)
try
{
	for (int i = 0; i < x; i++)
	{
		boost::mutex::scoped_lock lock(io_mutex);
		cout << "str:" << str << endl;
	}
}
catch (boost::thread_interrupted&)
{
	cout << "thread is interrupt" << endl;
}

int main()
{
	int x = 5;
	boost::thread tt(&Print,1,"hello thread");
	boost::thread_group gt;
	//創建線程
	gt.create_thread(bind(&Print,ref(x),"hello thread_group"));
	//等待線程退出
	gt.add_thread(&tt);
	gt.remove_thread(&tt);
	gt.join_all();
	boost::this_thread::sleep(boost::posix_time::seconds(2));
	system("pause");
	return 0;
}



想了解學習更多C++後臺服務器方面的知識,請關注:
微信公衆號:C++後臺服務器開發


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