boost线程的interruption

 

1. 创建一个boost线程对象

 

1.1  boost::thread(ThreadFunction);

 其中,ThreadFunction是线程的启动函数。创建完成这个对象后,线程就开始运行了。

 

1.2 如果启动函数有参数要传递,可以调用另一个线程对象构造器,boost::thread(ThreadFunction, Arg1, Arg2, ...);

也可以用绑定器,boost::thread(boost::bind(ThreadFunction, Arg1, Arg2 ...));

 

1.3 如果线程函数是一个对象的成员函数,可以用绑定器,boost::thread(boost::bind(&MyClass::ThreadFunction, MyObject));

MyClass是一个声明的类,MyObject是这个类的一个对象。

 

1.4 线程可以放到一个线程组里,这样可以统一管理。boost::thread_group

 

2. 线程的interrupt

 

2.1 从线程外部中断一个线程,可以调用线程对象的interrupt(),如下,其中_thread是一个boost::thread对象的share_ptr指针。声明为

 

 

 

2.2  interrupt检查点

如果在线程外部调用了_thread->interrupt(),线程内部的以下这些检查点可以抛出boost::thread_interrupted异常,通过捕获这个异常,我们可以知道线程被interrupt了。

boost::thread::join()

boost::thread::timed_join()

boost::thread::sleep()

boost::condition_variable::wait()

boost::condition_variable::timed_wait()

boost::condition_variable_any::wait()

boost::condition_variable_any::timed_wait()

boost::this_thread::sleep()

boost::this_thread::interruption_point()

 

2.3 限制interrupt区域

默认可以在线程的任何区域interrupt,boost::this_thread::disable_interruption di; 在这个对象有效区域不能被interrupt。

 {
    boost::this_thread::restore_interruption ri(di); ///< 这个可以暂时将interrupt打开
    boost::this_thread::interruption_point();
 }
另外,可以通过boost::thread::interruption_requested()来判断是否在线程外部有interrupt请求。
 
2.4  特别的情况
我在windows 2003操作系统下测试时发现,如果线程在非interrupt检查点被中断,程序退出,此时,系统会提示一个运行时错误。
windows xp下没有这个问题。
所以最好是除了我们要检查interruption的地方,其它的地方都要将其disable了。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值