当前位置: 首页 > news >正文

创建2个线程并执行(STL/Windows/Linux)

C++并发编程入门 目录

STL 写法

#include <thread>
#include <iostream>
using namespace std;void thread_fun1(void)
{cout << "one STL thread 1!" << endl;
}void thread_fun2(void)
{cout << "one STL thread 2!" << endl;
}int main(void)
{std::thread thread1(thread_fun1);std::thread thread2(thread_fun2);thread1.join();thread2.join();return 0;
}

Windows 写法

#include <iostream>
#include <windows.h>
using namespace std;DWORD WINAPI ThreadFun1(LPVOID lpParamter)
{cout << "one Windows thread 1!" << endl;return 0;
}
DWORD WINAPI ThreadFun2(LPVOID lpParamter)
{cout << "one Windows thread 2!" << endl;return 0;
}int main()
{HANDLE hThread1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);HANDLE hThread2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);HANDLE handleArr[] = { hThread1 , hThread2 };//等待两个线程结束WaitForMultipleObjects(2, handleArr, TRUE, INFINITE);CloseHandle(hThread1);CloseHandle(hThread2);return 0;
}

三次执行结果

每个线程都打印一句话

第一个线程和第二个线程交叉占用控制台

居然是先执行的第二个线程

Linux 写法

#include <pthread.h>
#include <iostream>
using namespace std;void* thread_fun1(void *arg)
{cout << "one Linux thread 1!" << endl;return 0;
}void* thread_fun2(void *arg)
{cout << "one Linux thread 2!" << endl;return 0;
}int main(void)
{pthread_t thread_id1;pthread_t thread_id2;pthread_create(&thread_id1, NULL, thread_fun1, NULL);pthread_create(&thread_id2, NULL, thread_fun2, NULL);//让线程运行直到结束pthread_join(thread_id1, NULL);pthread_join(thread_id2, NULL);return 0;
}

一次执行结果

另一次执行结果

http://www.lryc.cn/news/154718.html

相关文章:

  • Redis可以干什么
  • R语言+Meta分析;论文新方向
  • 实战系列(二)| MybatisPlus详细介绍,包含代码详解
  • 横向对比 npm、pnpm、tnpm、yarn 优缺点
  • 安防监控/视频汇聚/云存储/AI智能视频融合平台页面新增地图展示功能
  • 机器人中的数值优化(九)——拟牛顿方法(下)、BB方法
  • java 从resource下载excel打不开
  • NS2安装及入门实例——(ns2.35 / Ubuntu20.04)
  • 平面设计的三大基本元素 优漫动游
  • 【电子取证篇】汽车取证检验标准
  • 【元宇宙】游戏应用商城对元宇宙的影响
  • win10-docker-mysql镜像安装运行基础
  • VirtualBox7+Ubuntu22集群规划
  • 标绘一张图系统
  • 菜鸟教程《Python 3 教程》笔记(17):输入和输出
  • 【动态规划】面试题 08.01. 三步问题
  • mac常见问题(三) macbook键盘溅上水怎么办?
  • 安全测试目录内容合集
  • 数据结构和算法(1):开始
  • 线下沙龙 | 从营销扩张到高效回款,游戏公司如何通过全链路运营实现高质量出海!
  • 使用Jekyll + GitHub Pages搭建个人博客
  • ⽹络与HTTP 笔试题精讲1
  • 亲测有效:虚拟机安装gcc,报错Could not retrieve mirrorlist http://mirrorlist.centos.org
  • 机器人中的数值优化(十二)——带约束优化问题简介、LP线性规划
  • 如何解决使用 ISPC 构建编译项目代码的时候出现_ISPCAlloc、_ISPCLaunch、_ISPCSync的连接器错误
  • Hadoop 集群一直处于安全模式,强制退出后出现数据丢失警告。解决方法
  • 四旋翼飞行器基本模型(MatlabSimulink)
  • P1116 车厢重组(冒泡排序)
  • Android逆向学习(番外一)smali2java部分文件无法反编译的bug与修复方法
  • go语言基本操作---三