考虑以下示例代码,该代码创建一个线程并使用thread::interrupt
调用从主线程中断它:
#include <iostream>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <boost/ref.hpp>
int main()
{
boost::thread t([]{
int counter = 0;
while (1){
std::cout << "interruption enabled " << boost::this_thread::interruption_enabled() << std::endl;
try {
counter++;
if (counter % 5 == 0)
throw std::runtime_error("runtime error!");
std::cout << "thread function\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(300));
}
catch (boost::thread_interrupted &interruption)
{
std::cout << "oops!.. time to finish!" << std::endl;
return;
//std::cout << "...but couldn't o_O..." << std::endl;
}
catch (std::exception &e)
{
std::cout << "some exception: " << e.what() << std::endl;
}
}
});
boost::this_thread::sleep_for(boost::chrono::milliseconds(3000));
t.interrupt();
std::cout << "joinable: " << t.joinable() << std::endl;
if (t.joinable())
if (!t.try_join_for(boost::chrono::milliseconds(500)))
{
std::cout <<"still RUNNING\n detach it..." << std::endl;
t.detach();
}
std::cout << "main thread\n";
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
return 0;
}
现在,在OS X 10.10.3上编译时(默认情况下使用libc ++):
g++ main.cpp -I<path_to_boost_1_54_0> -std=gnu++11 -lboost_thread-mt -lboost_system-mt -lboost_chrono-mt -L<path_to_boost_1_54_0>/stage/lib
输出显示已启用中断:
interruption enabled 1
thread function
interruption enabled 1
thread function
...
但是,如果使用libstdc ++:
g++ main.cpp -I<path_to_boost_1_54_0> -std=gnu++11 -stdlib=libstdc++ -lboost_thread-mt -lboost_system-mt -lboost_chrono-mt -L<path_to_boost_1_54_0>/stage/lib
我得到输出,告诉我中断被禁用:
interruption enabled 0
thread function
interruption enabled 0
thread function
...
这种行为有原因吗?我使用了boost v1.54.0和这个LLVM v6.1.0:
$ g++ -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix
谢谢
答案 0 :(得分:1)
我在linux上重现了这个:
使用clang 3.5和libstdc ++它可以正常工作
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
some exception: runtime error!
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
thread function
interruption enabled 1
some exception: runtime error!
interruption enabled 1
thread function
interruption enabled 1
thread function
joinable: 1
oops!.. time to finish!
main thread
使用clang 3.5和libc ++它不起作用:
interruption enabled 128
thread function
oops!.. time to finish!
joinable: 1
Segmentation fault (core dumped)
我认为应该在增强列表中报告此问题。
升级开发者有可能表明它是libc ++中的一个错误