g++编译出的多线程程序出错“segmentation fault"
我使用的g++版本是g++ 4.4.3
升级到4.7版本:
add-apt-repository ppa:ubuntu-toolchain-r/test
apt-get update
apt-get install gcc-4.7-base
apt-get install gcc-4.7
apt-get install g++-4.7
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
update-alternatives --config gcc
重新编译:
g++ -std=c++0x A.cpp -o a
再次运行./a或者/tmp/a
再次错误:terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
Aborted
解决方法:
g++ -std=c++0x -pthread A.cpp -o a
再次运行./a或者/tmp/a
运行成功:
Launched from the main
Launched by thread 3
Launched by thread 4
Launched by thread 5
Launched by thread 6
Launched by thread 7
Launched by thread 8
Launched by thread 9
Launched by thread 2
Launched by thread 1
Launched by thread 0
代码例子:
#include <iostream> #include <thread> static const int num_threads = 10; //This function will be called from a thread void call_from_thread(int tid) { std::cout << "Launched by thread " << tid << std::endl; } int main() { std::thread t[num_threads]; //Launch a group of threads for (int i = 0; i < num_threads; ++i) { t[i] = std::thread(call_from_thread, i); } std::cout << "Launched from the main\n"; //Join the threads with the main thread for (int i = 0; i < num_threads; ++i) { t[i].join(); } return 0; }
代码来源: https://solarianprogrammer.com/2011/12/16/cpp-11-thread-tutorial/