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

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Using -pthread is not going to help in this case. I have the same environment, and the only solution is this
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

Comments

2

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

2 Comments

Correct. And I never knew why exactly, but this one explains it: stackoverflow.com/questions/18827938/… 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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.