boost::thread编程-线程中断

转自:http://blog.csdn.net/anda0109/article/details/41943691


thread的成员函数interrupt()允许正在执行的线程被中断,被中断的线程会抛出一个thread_interrupted异常,

它是一个空类,不是std::exception或boost::exception的子类。thread_interrupted异常应该在线程执行函数

里捕捉和处理,如果线程不处理这个异常,那么默认会中止线程的执行。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include "stdafx.h"  
  2. #include <windows.h>  
  3. #include <iostream>  
  4. #include <boost/thread.hpp>  
  5. #include <boost/atomic.hpp>  
  6.   
  7. boost::mutex io_mu;//io流操作锁  
  8.   
  9. void to_interrupt(boost::atomic_int &x,const std::string &str)  
  10. {  
  11.     try  
  12.     {  
  13.         for(int i=0;i<5;++i)  
  14.         {  
  15.             boost::this_thread::sleep(boost::posix_time::seconds(1));//等待1s  
  16.             //Sleep(1000);//等待1s  
  17.             boost::mutex::scoped_lock lock(io_mu);//锁定io流操作  
  18.             std::cout<<str<<++x<<std::endl;  
  19.         }  
  20.     }  
  21.     catch (boost::thread_interrupted& )//捕获线程中断异常  
  22.     {  
  23.         std::cout<<"thread interrupted!"<<std::endl;  
  24.     }  
  25. }  
  26.   
  27. int _tmain(int argc, _TCHAR* argv[])  
  28. {  
  29.     boost::atomic_int x(0);  
  30.     boost::thread t(to_interrupt,ref(x),"hello");  
  31.     boost::this_thread::sleep(boost::posix_time::seconds(2));//休眠2s  
  32.     t.interrupt();//要求线程中断执行  
  33.     t.join();//由于线程已经中断,所以立即返回  
  34.     getchar();  
  35.     return 0;  
  36. }  
程序运行结果如下:

hello1
hello2
thread interrupted!

由运行结果可知,线程在执行了两次循环之后中断执行。

上面程序中使用了boost::this_thread::sleep()函数,如果换成windows API函数Sleep(1000),重新运行,则发现线程并没有终止。读者可自行试验。

这就说明线程并不是在任何时候都可以中断的。

线程中断点:

线程并非在任何时候都可以中断的,thread库定义了若干个中断点,只有当线程执行到中断点的时候才可以被中断,一个线程可以有若干个线程中断点。

thread库定义了9个中断点,它们都是函数,如下:

thread::join();

thread::timed_join();
condition_variable::wait();
condition_variable::timed_wait();
condition_variable_any::wait();
condition_variable_any::timed_wait();
thread::sleep();

this_thread::sleep();

this_thread::interruption_point();

这些中断点的前8个都是某种形式的等待函数,表明线程在阻塞的时候可以被中断。而最后一个this_thread::interruption_point();则是一个特殊的中断点函数,它并不等待,只是起到一个标签的作用,表示线程执行到这个地方可以被中断。

注:在xp环境下使用this_thread::sleep的时候会报错,

      无法定位程序输入点GetTickCount64 在动态链接库kernel32.dll上 错误

解决方法:在stdafx.h中加 #define _WIN32_WINNT 0x0501

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值