boost库使用—线程类

584 阅读2分钟

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++后台服务器开发====