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?
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 ).
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.
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.
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).
You have to join
std::thread
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With