VS Code在ubuntu中执行多线程程序时报错:
问题描述:
最近在学习C++并发多线程,在ubuntu中使用VS Code编写多线程代码后,Ctrl+F5运行程序,结果出现了以下的问题:
#include<iostream>
#include<vector>
#include<thread>
using namespace std;
//一个单独的main函数,运行实际上是主线程在执行,主线程从main返回,则整个进程执行完毕
//自己创建的线程需要从一个函数开始运行
void MyPrint(){
cout<<"我的线程开始"<<endl;
////////
cout<<"我的线程结束了"<<endl;
}
int main(){
//此时这个代码中有两个线程在同时在执行,同时执行两个任务
thread mytobj(MyPrint);
mytobj.join();
cout<<"I love china"<<endl;
return 0;
}
> Executing task: C/C++: g++ 生成活动文件 <
正在启动生成...
/usr/bin/g++ -g /home/liukai/文档/Code_WorkSpace/CPP_CONCURRENCY/project.cpp -o /home/liukai/文档/Code_WorkSpace/CPP_CONCURRENCY/project
/usr/bin/ld: /tmp/ccb0x5iT.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
/usr/include/c++/9/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
生成已完成,但出现错误.
The terminal process terminated with exit code: -1.
Terminal will be reused by tasks, press any key to close it.
重点在于:
/usr/include/c++/9/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
原因分析:
百度之后,发现是 在ubuntu平台下调用pthread_create()函数,用gcc编译时出现Undefined reference to 'pthread_create’的问题。是因为pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
解决方案:
知道原因后问题就很好解决了,只需在每次编译时用gcc的-l选项将pthread库链接一下就行了。
但是能不能在VS Code里使其链接到这个静态库,然后直接Ctrl+F5直接运行,当然可以。
在VS Code的搜索框输入tasks.json,修改tasks.json文件。
把"args"修改为如下,在最后像命令行中一样加上“-lpthread”,保存后即可ctrl+F5运行多线程程序:
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}",
"-lpthread"
],