2011-08-07 45 views
2

我試圖防止它在特定範圍內的線程中斷。但是,使用boost::this_thread::disable_interruption di()似乎沒有任何效果。boost disable_interruption不會阻止thread_interrupted

#include <boost/thread.hpp> 
#include <iostream> 

void worker() { 
    std::cout << "START" << std::endl; 

    for(;;) { 
     { 
      boost::this_thread::disable_interruption di(); 
      try { 
       boost::this_thread::sleep(boost::posix_time::seconds(1)); 
      } 
      catch(boost::thread_interrupted & e) { 
       assert(false); 
      } 
     } 

     try { 
      boost::this_thread::interruption_point(); 
     } 
     catch(boost::thread_interrupted & e) { 
      break; 
     } 

    } 

    std::cout << "END" << std::endl; 
} 


int main() { 
    boost::thread thread(&worker); 
    thread.interrupt(); 
    thread.join(); 
} 

文檔似乎暗示boost::this_thread::sleep()不會拋出boost::thread_interrupteddi在範圍內。

我在做什麼錯?

回答

5

你應該在下面的行刪除括號:

//boost::this_thread::disable_interruption di(); 
boost::this_thread::disable_interruption di; 

而不是創造disable_interruption對象,你聲明的函數迪。

+0

謝謝,這解決了問題!雖然,你能解釋它是如何聲明一個函數的嗎? 'disable_interruption'是一種類型。 – Timesquare

+0

@Timesquare:這是一個有趣的問題。你可以閱讀它[這裏](http://stackoverflow.com/questions/1034606/is-there-any-use-for-local-function-declarations)。 –

+0

最煩人的解析:) – Kratz