Why does this simple std::thread example not work?

Tried the following example compiled with g++ -std=gnu++0x t1.cpp and g++ -std=c++0x t1.cpp but both of these result in the example aborting.

$ ./a.out 
terminate called after throwing an instance of 'std::system_error'
  what():  
Aborted

Here is the sample:

#include <thread>
#include <iostream>

void doSomeWork( void )
{
    std::cout << "hello from thread..." << std::endl;
    return;
}

int main( int argc, char *argv[] )
{
    std::thread t( doSomeWork );
    t.join();
    return 0;
}

I'm trying this on Ubuntu 11.04:

$ g++ --version
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2

Anyone knows what I've missed?


You have to join std::threads, just like you have to join pthreads.

int main( int argc, char *argv[] )
{
    std::thread t( doSomeWork );
    t.join();
    return 0;
}

UPDATE: This Debian bug report pointed me to the solution: add -pthread to your commandline. This is most probably a workaround until the std::thread code stabilizes and g++ pulls that library in when it should (or always, for C++).


Please use the pthread library during the compilation: g++ -lpthread.


Simplest code to reproduce that error and how to fix:

Put this in a file called s.cpp:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
  cout << "task1 says: " << msg;
}
int main(){
    std::thread t1(task1, "hello");
    usleep(1000000);
    t1.detach();
}

Compile like this:

el@apollo:~/foo7$ g++ -o s s.cpp -std=c++0x

Run it like this, the error happens:

el@apollo:~/foo7$ ./s
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted (core dumped)

To fix it, compile it like this with the -pthread flag:

g++ -o s s.cpp -std=c++0x -pthread
./s

Then it works correctly:

task1 says: hello