为什么没有try-catch就可以使this_thread :: interrupt工作正常?

时间:2014-10-06 12:21:25

标签: c++ multithreading boost

我测试了这段代码。两个线程thread_1每200毫秒打印一个字符串,thread_2在3秒内终止thread_1

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的尝试捕获,我在所有&#34; thread.hpp&#34;中搜索关键字catch。和&#34; thread_data.hpp&#34;但一无所获。

它是如何工作的?感谢。

1 个答案:

答案 0 :(得分: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;
            }
        }
    }