红联Linux门户
Linux帮助

g++编译出的多线程程序出错“segmentation fault"

发布时间:2015-11-27 10:32:24来源:linux网站作者:yangzhenping

我使用的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;
}


Linux下C/C++程序调试基础(GCC,G++,GDB,CGDB,DDD):http://www.linuxdiyf.com/linux/15853.html

几款好的C/C++编译器(编译器而非IDE):http://www.linuxdiyf.com/linux/14086.html

Linux下搭建C/C++开发环境(GTK):http://www.linuxdiyf.com/linux/11185.html

Linux中安装Eclipse进行C/C++开发:http://www.linuxdiyf.com/linux/10129.html