boost库中thread多线程详解5——谈谈线程中断

线程不是在任意时刻都可以被中断的。如果将线程中函数中的sleep()睡眠等待去掉,那么即使在主线程中调用interrupt()线程也不会被中断。
thread库预定义了若干个线程的中断点,只有当线程执行到中断点的时候才能被中断,一个线程可以拥有任意多个中断点。

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

1. thread::join();
2. thread::timed_join();
3. condition_variable::wait();
4. condition_variable::timed_wait();
5. condition_variable_any::wait();
6. condition_variable_any::timed_wait();
7. thread::sleep();
8. this_thread::sleep();
9. this_thread::interruption_point()
这些中断点中的前8个都是某种形式的等待函数,表明线程在阻塞等待的时候可以被中断。

而最后一个位于子名字空间this_thread的interruption_point()则是一个特殊的中断点函数,它并不等待,只是起到一个标签的作用,表示线程执行到这个函数所在的语句就可以被中断。看看下面的例子:

[cpp]   view plain copy print ?
  1. namespace  
  2. {  
  3.     boost::mutex io_mu;  
  4.   
  5.     void to_interrupt(const std::string& str)  
  6.     {  
  7.         // 如果在线程外部调用了this_thread->interrupt()  
  8.         // 线程内部的以下这些检查点可以抛出boost::thread_interrupted异常  
  9.         try  
  10.         {  
  11.             boost::this_thread::disable_interruption();  
  12.             for (int i = 0; i < 5; ++i)  
  13.             {  
  14.                 boost::mutex::scoped_lock lock(io_mu);  
  15.                 PRINT_DEBUG(i);  
  16.                 PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_enabled());  
  17.                 // PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_requested());  
  18.                 if (i == 2)  
  19.                 {  
  20.                     PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_enabled());  
  21.                     boost::this_thread::interruption_point();  
  22.                     PRINT_DEBUG(std::boolalpha << boost::this_thread::interruption_enabled());  
  23.                 }  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值