2

I have no idea why, but after including c++11 to my project in eclipse and working with the new features like std::array<>, it suddenly wont work when I use std::thread.

Here is the example I'm trying to run:

#include <iostream>
#include <string>
#include <thread>

void print_message_function(const std::string& msg);

int main()
{
    std::string message1 = "Thread 1";
    std::string message2 = "Thread 2";

    std::thread thread1(print_message_function, message1);
    std::thread thread2(print_message_function, message2);

    thread1.join();
    thread2.join();
}

void print_message_function(const std::string& msg)
{
    std::cout << msg << std::endl;
}

No error when compiling and no errors when running(no output too..), but when using the debug tool it crashes on this line:

std::thread thread1(print_message_function, message1);

this is the stack in the time of crash:

Thread [1] (Suspended: Signal 'SIGSEGV' received. Description: Segmentation fault.) 
    5 _dl_fixup()  0x0000003d6920df7c   
    4 _dl_runtime_resolve()  0x0000003d69214625 
    3 std::thread::_M_start_thread()  0x0000003d762b65a7    
    2 std::thread::thread<void (&)(std::string const&), std::string&>() /usr/include/c++/4.4.4/thread:133 0x0000000000402268    
    1 main() /.../Main.cpp:12 0x0000000000401e8d    

Why is this happening?

MoonBun
  • 4,322
  • 3
  • 37
  • 69
  • 1
    Did you link with `-pthread`? – Duck Dec 25 '13 at 14:54
  • Thread wraps the native threading lib which on linux is pthreads. Not sure how eclipse handles compile options but add `-pthread` at the end of your compile/link command. – Duck Dec 25 '13 at 15:01
  • Found a tutorial here: http://blog.asteriosk.gr/2009/02/15/adding-pthread-to-eclipse-for-using-posix-threads/ Now all works fine, thanks, post an answer so that question won't stay open forever. – MoonBun Dec 25 '13 at 15:07

1 Answers1

5

You need to link against the pthreads library with -pthread in your compile command.

Duck
  • 26,924
  • 5
  • 64
  • 92
  • 1
    Note, `-pthread` in not only for *linking* (Otherwise one could simply use `-lpthread`. See [this SO question](http://stackoverflow.com/questions/2127797/gcc-significance-of-pthread-flag-when-compiling) for more information. – juanchopanza Dec 25 '13 at 15:18