I got a strange core dump which I copied from a part of code in http://en.cppreference.com/w/cpp/thread/packaged_task,
#include
#include
I tried your first code snippet using the following version of g++:
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
and compiled with the following
g++ -o test_threads test_threads.cpp -std=c++11 -pthread
and I can run the program with no problems, and getting the following output:
$ ./test_threads
task_lambda: 512
If I then use the -lpthread
as you did with the following
g++ -o test_threads test_threads.cpp -std=c++11 -lpthread
I get
$ ./test_threads terminate called after throwing an instance of 'std::system_error'
what(): Unknown error -1
[1] 7890 abort ./test_threads
So please use -pthread
as a flag and not -lpthread
.
This behavior is also mentioned in the following
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59830
There's a difference between -pthread
and -lpthread
.
Looking at the man page for g++
-pthread
Adds support for multithreading with the pthreads library. This option sets flags for both the preprocessor and linker.
To have a look to what flags are activated for both one can check with the following:
g++ -dumpspecs | grep pthread
g++ -dumpspecs | grep lpthread
As one can clearly see, there are some preprocessor macros that are not activated if one is using -lpthread
.