我有以下代码:
#include <cstdio>
#include <boost/thread.hpp>
void foo() {
puts("foo()");
}
int main() {
boost::thread t(foo);
//t.start_thread();
puts("join()");
t.join();
return 0;
}
它工作正常,但是当我取消注释 start_thread()
时,它会在 join()
中崩溃。
为什么 start_thread()
调用会导致 join()
中出现段错误?
我使用:
g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Boost Version: 1.54.0.1ubuntu1
g++ -std=c++11 -static main.cpp -lboost_thread -lboost_system -lpthread -L/usr/lib/x86_64-linux-gnu/
最佳答案
Boost线程在boost::thread
的构造函数中执行,没有必要也不应该显式启动它。实际上,boost::thread
的ctor调用了start_thread()
,start_thread()
调用了start_thread_noexcept()
,其中实现了不同平台上线程的创建,如果使用pthread
,它会调用pthread_create()
,可以从boost thread的源码中查看。我想知道为什么这个函数是公开的。
更新:刚刚查看了新版本的boost(1.57),该函数现在被声明为私有(private),在文件boost/thread/detail/thread.hpp
中:
private:
bool start_thread_noexcept();
bool start_thread_noexcept(const attributes& attr);
//public:
void start_thread()
{
if (!start_thread_noexcept())
{
boost::throw_exception(thread_resource_error());
}
}
void start_thread(const attributes& attr)
{
if (!start_thread_noexcept(attr))
{
boost::throw_exception(thread_resource_error());
}
}
所以如果你想调用它,它会编译失败。
关于c++ - join() 上的 Boost 线程段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27119785/