C++ boost thread学习(一)

 

线程中断 

在一个线程对象上调用 interrupt() 会中断相应的线程,并会在这个线程中抛出一个类型为 boost::thread_interrupted 的异常。 

如果给定的线程不包含任何中断点,简单调用interrupt就不会起作用。 每当一个线程中断点,它就会检查interrupt是否被调用过。只有被调用过了, boost::thread_interrupted 异常才会相应地抛出。 

Boost.Thread定义了一系列的中断点,例如sleep() 函数,由于sleep() 在这个例子里被调用了五次,该线程就检查了五次它是否应该被中断。然而sleep()之间的调用,却不能使线程中断。 

一旦该程序被执行,它只会打印三个标准输出流。这是由于在main里3秒后调用 interrupt()方法。 因此,相应的线程被中断,并抛出一个 boost::thread_interrupted 异常。这个异常在线程内也被正确地捕获,catch 处理是空的。

Boost.Thread定义包括上述 sleep()函数等十个中断。 有了这些中断点,线程可以很容易及时中断。然而,他们并不总是最佳的选择,因为中断点必须事前读入以检查 boost::thread_interrupted 异常。 

C++代码  收藏代码
  1. #include <boost/thread.hpp>  
  2. #include <boost/thread/mutex.hpp>  
  3.   
  4. #include <iostream>  
  5.   
  6. boost::mutex io_mutex;  
  7.   
  8. using namespace std;  
  9.   
  10. void wait(int seconds)  
  11. {  
  12. boost::this_thread::sleep(boost::posix_time::seconds(seconds));  
  13. }  
  14.   
  15. void interruptedThread()  
  16. {  
  17.     try  
  18.     {  
  19.         for (int i = 0; i < 5; i++)  
  20.         {  
  21.             wait(1);  
  22.             cout << i << endl;  
  23.         }  
  24.     }  
  25.     catch (boost::thread_interrupted&)  
  26.     {  
  27.         cout << "thread_interrupted exception happened";  
  28.     }  
  29. }  
  30.   
  31. void testInteruptedThread()  
  32. {  
  33.     boost::thread t(interruptedThread);  
  34.     wait(3);  
  35.     t.interrupt();  
  36.     t.join();  
  37. }  
  38.   
  39. int main(int argc, char* argv[])  
  40. {  
  41.     testInteruptedThread();  
  42.     return 0;  
  43. }  
原文地址:https://www.cnblogs.com/fire909090/p/6801539.html