[ACCEPTED]-Why does this simple std::thread example not work?-c++11

Accepted answer
Score: 46

You have to join std::threads, just like you have to join 5 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 4 commandline. This is most probably a workaround 3 until the std::thread code stabilizes and g++ pulls 2 that library in when it should (or always, for 1 C++).

Score: 13

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

Score: 3

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 3 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 2 fix it, compile it like this with the -pthread 1 flag:

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

Then it works correctly:

task1 says: hello
Score: 0

For what it's worth, I had different issue with similar code using 6 threads in g++ (MinGW). Work-around was to put 5 some "delay" between creating 4 a thread and joining it.

Code with infrequently 3 failing assertion:

std::atomic_bool flag{false};
std::thread worker( [&] () { flag.store(true); } );
worker.join();
assert(flag.load()); // Sometimes fails

Work-around:

std::atomic_bool flag{false};
std::thread worker( [&] () { flag.store(true); } );
while (not flag.load()) { std::this_thread::yield(); }
worker.join();
assert(flag.load()); // Works fine

Note that 2 yield() alone did not help, hence the while loop. Using 1 sleep_for(...) also works.

More Related questions