boost之thread

1.boost里的thread创建之后会立即启动。

代码示例:

#include <iostream>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
using namespace boost;


mutex io_mu;
void printing(int& x,const string str)
{
	for (int i = 0;i < 5;++i)
	{
		mutex::scoped_lock lock(io_mu);
		cout << str << ++x <<endl;
	}
}

int main()
{
	int x = 0;
	thread(printing,x,"hello");
	thread(printing,x,"boost");
	this_thread::sleep(posix_time::seconds(2));
	return 0;
	
}

 2.主线程等待和线程分离,为了防止主线程在子线程未执行完时就退出,可以使用posix_time::seconds和timed_join以及join

#include <iostream>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
using namespace boost;


mutex io_mu;
void printing(int& x,const string str)
{
	for (int i = 0;i < 5;++i)
	{
		mutex::scoped_lock lock(io_mu);
		cout << str << ++x <<endl;
	}
}

int main()
{
	int x = 0;
	thread t1(printing,x,"hello");
	thread t2(printing,x,"boost");
	//this_thread::sleep(posix_time::seconds(2));
	t1.timed_join(posix_time::seconds(1));
	t2.join();
	t1.detach();
	return 0;
	
}

 3.操作线程,获取线程id和获得可并行(非并发)执行的线程数量。

#include <iostream>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
using namespace boost;


mutex io_mu;
void printing(int& x,const string str)
{
	for (int i = 0;i < 5;++i)
	{
		mutex::scoped_lock lock(io_mu);
		cout << str << ++x <<endl;
	}
}

int main()
{
	int x = 0;
	thread t1(printing,x,"hello");
	thread t2(printing,x,"boost");

	cout << t1.get_id()<<endl;
	cout << thread::hardware_concurrency()<<endl;
	this_thread::sleep(posix_time::seconds(2));
	
	return 0;
	
}

 4.线程中断

代码示例:

#include <iostream>
#include <string>
#include <vector>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
using namespace boost;


mutex io_mu;
void to_interrupt(int& x,const string str)
try
{
	for (int i = 0;i < 5;++i)
	{
		this_thread::sleep(posix_time::seconds(1));
		mutex::scoped_lock lock(io_mu);
		cout << str << ++x <<endl;
	}
}
catch(thread_interrupted&)
{
	cout << "thread_interrupted" <<endl;
}

int main()
{
	int x = 0;
	thread t(to_interrupt,x,"hello boost");
	
	this_thread::sleep(posix_time::seconds(4));
	t.interrupt();
	t.join();
	
	return 0;
	
}

 5.线程组

线程组可以看做是线程池,内部是使用顺序容器list<thread*>存放tread的指针。

#include <iostream>
#include <string>
#include <vector>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
using namespace std;
using namespace boost;

mutex io_mu;
void printing(int& x,const string str)
{
	for (int i = 0;i < 5;++i)
	{
		mutex::scoped_lock lock(io_mu);
		cout << str << ++x <<endl;
	}
}

int main()
{
	int x = 0;
	thread_group tg;
	tg.create_thread(bind(printing,x,"C++"));
	tg.create_thread(bind(printing,x,"BOOST"));
	tg.join_all();
	return 0;
	
}
原文地址:https://www.cnblogs.com/liuweilinlin/p/3256206.html