C++: Core dump with packaged_task

后端 未结 1 1166
遥遥无期
遥遥无期 2021-01-12 19:02

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 

        
相关标签:
1条回答
  • 2021-01-12 20:06

    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.

    0 讨论(0)
提交回复
热议问题