Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 thread error runtime

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

like image 330
David C Avatar asked Oct 14 '13 11:10

David C


People also ask

What is multithreading C ++ 11?

Multithreading in C++ C++ 11 did away with all that and gave us std::thread. The thread classes and related functions are defined in the thread header file. std::thread is the thread class that represents a single thread in C++.

How do you stop a thread in C++?

The C++11 does not have direct method to terminate the threads. The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.

How do you destroy STD thread?

You could call std::terminate() from any thread and the thread you're referring to will forcefully end. You could arrange for ~thread() to be executed on the object of the target thread, without a intervening join() nor detach() on that object.

How many threads can be executed at a time in CPP?

There is nothing in the C++ standard that limits number of threads. However, OS will certainly have a hard limit. Having too many threads decreases the throughput of your application, so it's recommended that you use a thread pool.


2 Answers

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.

like image 154
Daniel Frey Avatar answered Sep 30 '22 00:09

Daniel Frey


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
like image 28
log0 Avatar answered Sep 30 '22 01:09

log0