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
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++.
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.
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.
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With