Search code examples
c++c++11stdthread

Why this program throws 'std::system_error'?


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

Code:

#include <iostream>
#include <thread>

void f()
{
  std::cout << "hi thread" << std::endl;
}

int main()
{
  std::thread t(f);
  std::cout << "hi" << std::endl;
  t.join();
}

Issue:

$ g++ -o thread_test thread_test.cpp -std=c++0x
$ ./thread_test         
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Abortado

"Abortado" means "aborted" in my locale.


Solution

  • You should link it to pthread:

    g++ -o thread_test thread_test.cpp -std=c++0x -lpthread
    

    libstdc++'s std::thread implementation requires you to link your applications to libpthread, otherwise they'll throw a std::system_error when you try to create a thread.