Why does this simple std::thread example not work?

后端 未结 5 602
无人及你
无人及你 2020-12-01 02:41

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.

5条回答
  •  粉色の甜心
    2020-12-01 03:33

    Simplest code to reproduce that error and how to fix:

    Put this in a file called s.cpp:

    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    void task1(std::string msg){
      cout << "task1 says: " << msg;
    }
    int main(){
        std::thread t1(task1, "hello");
        usleep(1000000);
        t1.detach();
    }
    

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

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

    Then it works correctly:

    task1 says: hello
    

提交回复
热议问题