Search code examples
c++boostboost-thread

Boost Thread segmentation fault on join()


I have following piece of code:

#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;
}

It works fine, but when I uncomment start_thread() call it crushes in join().

Why does the start_thread() call cause segmentation fault in join()?

I use:

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/


Solution

  • Boost thread gets executed in the constructor of boost::thread, there is no need and should not to start it explicitly. Actually, the ctor of boost::thread calls start_thread(), start_thread() calls start_thread_noexcept() which implements the creation of thread on different platforms, it calls pthread_create() if you use pthread, you can check this from the source code of boost thread. I'm wondering why this function is public.
    Update: just checked out the new version of boost(1.57), this function is declared as private now, in the file 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());
          }
        }
    

    so it will fail to compile if you want to call it.