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

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

C++并发编程入门 目录

STL 写法

#include <thread>
#include <iostream>
using namespace std;void thread_fun(int arg)
{cout << "one STL thread " << arg << " !" << endl;
}int main(void)
{int thread_count = 10;int id_array[10] = { 1,2,3,4,5,6,7,8,9,10 };std::thread thread_arr[10] = { };for (int i = 0; i < thread_count; i++){thread_arr[i] = std::thread(thread_fun, id_array[i]);}for (int i = 0; i < thread_count; i++){thread_arr[i].join();}return 0;
}

Windows 写法

#include <iostream>
#include <windows.h>
using namespace std;DWORD WINAPI ThreadFun(LPVOID lpParamter)
{//转成整数地址,再对地址解引用取出整数cout << "one Windows thread "<< *(int*)lpParamter<<" !" << endl;return 0;
}int main()
{int thread_count = 10;HANDLE handleArr[10] = {NULL};//给线程函数传递的数据,用来标记线程int data[10] = { 1,2,3,4,5,6,7,8,9,10 };for (int i = 0; i < 10; i++){handleArr[i] = CreateThread(NULL, 0, ThreadFun, &data[i], 0, NULL);}//等待10个线程结束WaitForMultipleObjects(thread_count, handleArr, TRUE, INFINITE);for (int i = 0; i < thread_count; i++){CloseHandle(handleArr[i]);}return 0;
}

一次执行结果


 

另一次执行结果

Linux 写法

#include <pthread.h>
#include <iostream>
using namespace std;void* thread_fun(void *arg)
{cout << "one Linux thread "<< *(int*)arg<<" !" << endl;return 0;
}int main(void)
{int thread_count = 10;int id_array[10] = { 1,2,3,4,5,6,7,8,9,10 };pthread_t thread_arr[10] = { 0 };for (int i = 0; i < thread_count; ++i){pthread_create(&thread_arr[i], NULL, thread_fun, &id_array[i]);}//让线程运行直到结束for (int i = 0; i < thread_count; i++){pthread_join(thread_arr[i], NULL);}return 0;
}

一次执行结果

另一次的执行结果

再一次执行结果

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

相关文章:

  • 三、创建各个展示模块组件
  • 推荐一款程序员截图神器!
  • 无涯教程-JavaScript - IMCSC函数
  • Ubuntu22.04 LTS 显卡相关命令
  • 《TCP/IP网络编程》阅读笔记--基于 TCP 的半关闭
  • Rust的模块化
  • vmware设置桥接模式后ip设置
  • 算法通关村第十七关:白银挑战-贪心高频问题
  • 目标检测评估指标mAP:从Precision,Recall,到AP50-95
  • 七大排序算法
  • GitHub two-factor authentication
  • un-app-手机号授权登录-授权框弹不出情况
  • 手写Spring:第14章-自动扫描Bean对象注册
  • redux中间件的简单讲解
  • 嵌入式开发-绪论
  • 大数据知识合集之预处理方法
  • mysql(九)mysql主从复制
  • nodejs采集淘宝、天猫网商品详情数据以及解决_m_h5_tk令牌及sign签名验证(2023-09-09)
  • 虚拟机上部署K8S集群
  • 设计模式 - 责任链
  • 【小沐学Unity3d】3ds Max 骨骼动画制作(CAT、Character Studio、Biped、骨骼对象)
  • CUDA说明和安装[window]
  • sqlserver2012性能优化配置:设置性能相关的服务器参数
  • 介绍 dubbo-go 并在Mac上安装,完成一次自己定义的接口RPC调用
  • 目标检测数据集:摄像头成像吸烟检测数据集(自己标注)
  • Unity的UI管理器
  • Mp4文件提取详细H.264和MP3文件
  • Qt应用程序连接达梦数据库-飞腾PC麒麟V10
  • 2023-09-03 LeetCode每日一题(消灭怪物的最大数量)
  • 绘图 | MATLAB