2014-10-06 94 views
1

我使用此代码进行了测试。两个线程thread_1每200毫秒打印一个字符串,thread_2在3秒内终止thread_1为什么升压this_thread :: interrupt可以在没有try-catch的情况下工作?

int main() { 
    boost::thread t1([&]() { 
     while(1) { 
      boost::this_thread::interruption_point(); 
      cout << "t1 running" << endl; 
      Sleep(200); 
     } 
     cout << "it never goes here" << endl; 
    }); 
    boost::thread t2([&]() { 
     Sleep(3000); // wait 3 seconds to terminate thread 1 
     cout << "interrupt t1" << endl; 
     t1.interrupt(); // thread 1 should raise a thread_interrupted exception ? 
    }); 

    t1.join(); 
    t2.join(); 
    Sleep(5000); // sleep 5 seconds waiting for the crash 
} 

我希望代码崩溃,但事实并非如此。然后我猜boost::thread有一个try-catch,我在所有的“thread.hpp”和“thread_data.hpp”中搜索关键字catch,但什么也没找到。

它是如何工作的?谢谢。

回答

4

库实现(源文件,而不是头文件)包含处理错误的代理函数。

正如你可以在phtreads变型看,它也做了一些其他管家:http://www.boost.org/doc/libs/1_56_0/libs/thread/src/pthread/thread.cpp

namespace 
    { 
     extern "C" 
     { 
      static void* thread_proxy(void* param) 
      { 
       boost::detail::thread_data_ptr thread_info = static_cast<boost::detail::thread_data_base*>(param)->self; 
       thread_info->self.reset(); 
       detail::set_current_thread_data(thread_info.get()); 
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS 
       BOOST_TRY 
       { 
#endif 
        thread_info->run(); 
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS 

       } 
       BOOST_CATCH (thread_interrupted const&) 
       { 
       } 
// Removed as it stops the debugger identifying the cause of the exception 
// Unhandled exceptions still cause the application to terminate 
//     BOOST_CATCH(...) 
//     { 
//     throw; 
// 
//      std::terminate(); 
//     } 
       BOOST_CATCH_END 
#endif 
       detail::tls_destructor(thread_info.get()); 
       detail::set_current_thread_data(0); 
       boost::lock_guard<boost::mutex> lock(thread_info->data_mutex); 
       thread_info->done=true; 
       thread_info->done_condition.notify_all(); 

       return 0; 
      } 
     } 
    } 
相关问题