7

My programs looks like below

#include <iostream>
#include <thread>
#include <exception>

void hello()
{
    std::cout << "Hello world!!!!" << std::endl;
}

int main()
{
    std::cout << "In Main\n";
    std::thread t(hello);
    t.join();
    return 0;
}

When I compile it using the following command I get no errors

g++-4.7 -std=c++11 main.cpp

But when I run it I get the following error

In Main
terminate called after throwing an instance of 'std::system_error'
what():  Operation not permitted
Aborted (core dumped)

Could someone help me with where I am going wrong?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Alwin Doss
  • 962
  • 2
  • 16
  • 33
  • it most probably won't be the root cause of the error message you see, but std::cout (and others) are not supposed to be used concurrently without access serialization – bobah Nov 05 '12 at 07:15
  • @bobah - there's no concurrent use here. The insertion in `main()` finished before the thread is created. – Pete Becker Nov 05 '12 at 13:11
  • @PeteBecker - that's precisely why I said "most probably won't be" – bobah Nov 05 '12 at 14:02

5 Answers5

10

When I use C++11 threads with GCC, i use:

g++ -std=c++0x -pthread -g main.cpp

That works for me.

Dan
  • 12,157
  • 12
  • 50
  • 84
Michael McGuire
  • 1,034
  • 9
  • 20
6

When compiling your code with g++, use the -pthread option.

Below is the answer I find from stackoverflow: In g++ is C++ 11 thread model using pthreads in the background?

Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
3

Everybody already answered that you need the -pthread argument passed to the compiler. Almost for sure it won't change in 4.8 but according to http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52681 the exception will at least have a nice message stating what's wrong.

0

You might need to link against the pthread library

gvd
  • 1,823
  • 13
  • 18
0

You can try with,

g++ --std=c++11 -lpthread main.cpp
Andy
  • 49,085
  • 60
  • 166
  • 233