社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
一、编写代码如下,取名为hello.c或者hello.cpp均可
#include <iostream>
#include <thread>
using namespace std;
void show(int i)
{
cout <<"now the show is "<<i<<endl;
}
int main()
{
for(int i=0;i<10;i++)
{
thread t1(show,i);
t1.detach();
}
return 0;
}
二、编译
g++ -c -g hello.c (-c指conplier,-p指debug模式),此步之后将生成hello.o程序
g++ hello.o -o hello.exe -lpthread (-o hello.exe指的是-out为hello.exe的文件,由于pthread不是linux下的默认的库,也就是在链 接的时候,无法找到phread库中哥函数的入口地址,因此要加-lpthread否则链接失败)
运行./hello.exe查看结果
三、结果分析
注意看,有的时候同样的输出竟然 会出现两次,有的时候什么也没有输出
若将代码中的detach()改为join(),则程序结果很有规律,如下图:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!