1.出现场景
第一次遇见这个问题是使用thread
库做多线程时,
#include <iostream>
#include <thread>
#include <unistd.h>
using namespace std;
void thread1(){
cout << "thread 01:" << endl;
for(int i = 0; i < 10; i++){
cout << "t1:" << i << endl;
}
}
void thread2(){
cout << "thread 02:" << endl;
for(int i = 10; i > 0; i--){
cout << "t2:" << i << endl;
}
}
int main(int argc, char** argv){
thread task1(thread1);
thread task2(thread2);
task1.join();
task2.join();
sleep(1);
return 0;
}
代码没一点毛病,使用g++编译时,第一次
g++ main.cpp -o thread
结果直接编译报错,
In file included from /usr/local/include/c++/4.9.3/thread:35:0,
from main.cpp:2:
/usr/local/include/c++/4.9.3/bits/c++0x_warning.h:32:2: 错误:#error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
#error This file requires compiler and library support for the \
^
main.cpp: 在函数‘int main(int, char**)’中:
main.cpp:24:5: 错误:‘thread’在此作用域中尚未声明
thread task01(thread01);
^
main.cpp:25:12: 错误:expected ‘;’ before ‘task02’
thread task02(thread02);
^
main.cpp:27:5: 错误:‘task01’在此作用域中尚未声明
task01.join();
^
main.cpp:28:5: 错误:‘task02’在此作用域中尚未声明
task02.join();
^
这个问题之前遇到比较多,比较老的编译器可能不支持C++11的内容,而thread是c++11里面的,因此重新编译
g++ main.cpp -o thread -std=c++11
结果编译通过,运行时报错
[root@localhost thread]# ./thread
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
已放弃 (core dumped)
刚开始比较懵逼,去查了一下std::system_error
的错误,发现是thread动态库没有链接成功,再次编译
g++ main.cpp -o thread -std=c++11 -lpthread
运行正确。
[root@localhost thread]# ./thread
thread 02:
t2:10
t2:9
t2:8
t2:7
t2:6
t2:5
t2:4
t2:3
t2:2
t2:1
thread 01:
t1:0
t1:1
t1:2
t1:3
t1:4
t1:5
t1:6
t1:7
t1:8
t1:9
2.解决方法
编译时添加-lpthread 或-pthread参数