C++ boost thread學習(一)

來源:互聯網
上載者:User

標籤:tin   com   cep   second   key   app   std   技術分享   列印   

 線程中斷 

在一個線程對象上調用 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. }  

C++ boost thread學習(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.