在用g++ 4.8.2编译C++11的线程代码后,运行时遇到了如下报错:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)
我们先看一下代码:
1 #include <boost/atomic.hpp> 2 #include <thread> 3 #include <iostream> 4 5 boost::atomic<int> a{0}; 6 7 void thread() 8 { 9 ++a; 10 } 11 12 int main() 13 { 14 std::thread t1{thread}; 15 std::thread t2{thread}; 16 t1.join(); 17 t2.join(); 18 std::cout << a << ' '; 19 }
之前用的编译命令为:
/opt/compiler/gcc-4.8.2/bin/g++ test.cpp -I ./boost/include -std=c++11
需要改为:
/opt/compiler/gcc-4.8.2/bin/g++ test.cpp -I ./boost/include -std=c++11 -lpthread -Wl,--no-as-needed
这样运行就不会报错了。
本文参考自:https://stackoverflow.com/questions/19463602/compiling-multithread-code-with-g#