2011-08-07 46 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