標籤: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++代碼
- #include <boost/thread.hpp>
- #include <boost/thread/mutex.hpp>
-
- #include <iostream>
-
- boost::mutex io_mutex;
-
- using namespace std;
-
- void wait(int seconds)
- {
- boost::this_thread::sleep(boost::posix_time::seconds(seconds));
- }
-
- void interruptedThread()
- {
- try
- {
- for (int i = 0; i < 5; i++)
- {
- wait(1);
- cout << i << endl;
- }
- }
- catch (boost::thread_interrupted&)
- {
- cout << "thread_interrupted exception happened";
- }
- }
-
- void testInteruptedThread()
- {
- boost::thread t(interruptedThread);
- wait(3);
- t.interrupt();
- t.join();
- }
-
- int main(int argc, char* argv[])
- {
- testInteruptedThread();
- return 0;
- }
C++ boost thread學習(一)