5

Hello I have problem with threads in C++11. I have ubuntu 64bit 13.10(testing) with g++ 4.8.1. I tried to compile code:

#include <thread>

void func()
{
   // do some work
}

int main()
{
   std::thread t(func);
   t.join();
   return 0;
}

with options: -std=c++11 -pthread -lpthread. Compilation was successful, but when I tried to run it, I've received an error:

terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
David C
  • 51
  • 1
  • 2

3 Answers3

6

I think the other answers are a bit misleading. What is important is that you only need -pthread. The order of this flag is not important!

-pthread will automatically link with libpthread and it'll do so correctly. Note that you need to provide this option both when compiling and linking your code (except when you do everything at once, of course).

Only when you provide -lpthread explicitly, the order of where you put might be important, but as already mentioned, you shouldn't add it explicitly when using -pthread.

Daniel Frey
  • 55,810
  • 13
  • 122
  • 180
  • Using `-pthread` is not going to help in this case. I have the same environment, and the only solution is [this](http://stackoverflow.com/a/19359353/476681) – BЈовић Oct 25 '13 at 13:55
5

You probably have the same problem as mentioned here:
https://bugs.launchpad.net/ubuntu/+source/gcc-defaults/+bug/1228201

Add this flag to your command line. It will force g++ to link with the given libraries.

-Wl,--no-as-needed
log0
  • 10,489
  • 4
  • 28
  • 62
2

It seems that order matters, or atleast, that's what is said in this thread: C++ Threads, std::system_error - operation not permitted?

Community
  • 1
  • 1
Bolke
  • 107
  • 9
  • 1
    Correct. And I never knew why _exactly_, but this one explains it: http://stackoverflow.com/questions/18827938/strange-g-linking-behavior-depending-on-arguments-order Basically, if you use `-lwhatever` _before_ the file that needs the library, the linker discards it since it didn't see any of the symbols used so far. – stefan Oct 14 '13 at 11:26
  • yes linked libraries must be on the right of the file that needs it. But is it really the problem of the OP ? Seems that other people have the same issue on Ubuntu 13.10. – log0 Oct 14 '13 at 11:30