gpt4 book ai didi

c++ - 为什么 boost this_thread::interrupt 可以在没有 try-catch 的情况下工作?

转载 作者:行者123 更新时间:2023-11-30 01:51:20 24 4
gpt4 key购买 nike

我用这段代码进行了测试。两个线程,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 的 try-catch,我在所有“thread.hpp”和“thread_data.hpp”中搜索关键字 catch 但一无所获.

它是如何工作的?谢谢。

最佳答案

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

正如您在 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;
}
}
}

关于c++ - 为什么 boost this_thread::interrupt 可以在没有 try-catch 的情况下工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26216136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com