c++ - join() 上的 Boost 线程段错误

标签 c++ boost boost-thread

我有以下代码:

#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/

相关文章:

c++ - 防止构造函数参数隐式转换为外部库类型

c++ - 加入后线程上的共享指针计数为 1?

c++ - 如何测试一行是否为空?

c++ - 我们如何使用 Visual Studio 2013 在 C++ 中访问变更集编号?

c++ - 创建一个返回 std::mem_fn 或 boost::mem_fn 的通用包装器

c++ - 当没有更多引用时如何从缓存中删除智能指针?

c++ - CSV 格式不正确

c++ - C++中的前向声明错误

multithreading - 避免在构建 Boost 1.63.0 期间失败 - 线程

c++ - 线程终止后出现 Qt 主窗口