Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 345
Stéphane Avatar asked Jun 26 '11 17:06

Stéphane


People also ask

Can STD thread fail?

std::thread::join() is permitted to fail, throwing a std::system_error for no_such_process if the thread is "not valid". Note that the no_such_process case is distinct from a thread that is not joinable (for which the error code is invalid_argument ).

How do I execute a thread in C++?

To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object. Once the object is created a new thread is launched which will execute the code specified in callable. After defining callable, pass it to the constructor.

What happens if I don't join a thread C++?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything. But this some point is non-deterministic.

What does std :: thread do?

std::thread Threads allow multiple functions to execute concurrently. std::thread objects may also be in the state that does not represent any thread (after default construction, move from, detach, or join), and a thread of execution may not be associated with any thread objects (after detach).


2 Answers

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++).

like image 115
rubenvb Avatar answered Sep 20 '22 02:09

rubenvb


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

like image 21
SarB Avatar answered Sep 22 '22 02:09

SarB