linux下c++多线程测试程序Demo - Go语言中文社区

linux下c++多线程测试程序Demo


 一、编写代码如下,取名为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(),则程序结果很有规律,如下图:

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/Johnisjohn/article/details/97189197
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 15:53:12
  • 阅读 ( 685 )
  • 分类:Linux

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢