quickbug quickbug - 1 year ago 127
C++ Question

thread with code::blocks error at runtime

Compile this file:

//Create a C++11 thread from the main program

#include <iostream>
#include <thread>

//This function will be called from a thread
void call_from_thread()
std::cout << "Hello, from thread! " << std::endl;

int main()
std::cout << "Hello, from main! " << std::endl;

//Launch a thread
std::thread t1(call_from_thread);

//Join the thread with the main thread

return 0;

using code::blocks with the copmpiler option "use C++11" checked.

code::blocks compiler says: g++ -Wall -fexceptions -g -std=c++11 -pthread -c /home/main.cpp -o obj/Debug/main.o

note that the -std=c++11 -pthread was passed to the compiler.

When running the programm,got this message:

Hello, from main!
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)

Process returned 134 (0x86) execution time : 0.110 s
Press ENTER to continue.

how to get this work?
thanks for helping.


PS. I have seen this post Compiling multithread code with g++. Then tried to use the trick

I tried this:

g++ -Wall -fexceptions -g -std=c++11 -pthread -Wl --no-as-needed -c /home/olivier/main.cpp -o obj/Debug/main.o

but got the following.

g++: error: unrecognized command line option ‘-Wl’
g++: error: unrecognized command line option ‘--no-as-needed’

Answer Source

If you compile with -pthread you should link with -lpthread.

The second is easy, it must be:-Wl,--no-as-needed (',' is missing), but it is used for the linker. Your call only compiles into an object file, so you can erase that.

Another note on the second one, it might be that you actually have to link with -Wl,--no-as-needed due to a bug in some gcc version

As for Code::Blocks, you can add -Wl,--no-as-needed and -lpthread in the linker tab of the build options.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download