5
votes

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

3
Could you try with -pthread -std=c++11 ? (without -lpthread)sphair
Seems that other people have this issue bugs.launchpad.net/ubuntu/+source/gcc-defaults/+bug/1228201log0

3 Answers

6
votes

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.

5
votes

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
2
votes

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