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;
}



  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值