C++ Boost 多线程(三),线程的中断

 
 

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

using namespace std;

void func1(const int &id)
{
	cout<<"thread #"<<id<<" start..."<<endl;
	//sleep不会放弃时间片
	boost::thread::sleep(boost::get_system_time()+boost::posix_time::seconds(3));
	cout<<"thread #"<<id<<" end"<<endl;
}

void func2(const int &id)
{
	cout<<"thread #"<<id<<" start..."<<endl;
	//预定义中断点,主动放弃时间片
	boost::thread::yield();
	cout<<"thread #"<<id<<" end"<<endl;
}

void func3(const int &id)
{
	cout<<"thread #"<<id<<" start..."<<endl;
	//预定义中断点
	boost::this_thread::interruption_point();
	cout<<"thread #"<<id<<" end"<<endl;
}

//线程中断
int main()
{
	boost::thread t1(func1, 11);
	t1.interrupt();
	boost::thread t2(func2, 22);
	t2.interrupt();
	boost::thread t3(func3, 33);
	t3.interrupt();

	t1.join();
	t2.join();
	t3.join();

	system("pause");
	return 0;
}

说明:结果显示只有线程2不会被中断


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

using namespace std;

void print(const int &id)
{
	//创建一个不可被中断的对象
	boost::this_thread::disable_interruption di;
	cout<<boost::this_thread::interruption_enabled<<endl;
	cout<<"thread #"<<id<<" start..."<<endl;
	boost::thread::sleep(boost::get_system_time()+boost::posix_time::seconds(3));
	for (int i=1; i<11; ++i)
	{
		cout<<"i="<<i<<"   ";
	}

	cout<<endl;
	boost::this_thread::restore_interruption ri(di);//到这里为止对象不可被中断
	cout<<boost::this_thread::interruption_enabled<<endl;
}

int main()
{

	boost::thread t1(print, 11);
	boost::thread t2(print, 22);
	boost::thread t3(print, 33);
	t3.interrupt();

	t1.join();
	t2.join();
	t3.join();

	system("pause");
	return 0;
}



猜你喜欢

转载自blog.csdn.net/u012592062/article/details/80467527