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

C++启动线程的方法

(1)函数指针
情况一:主线程有join,正常执行

#include <thread>
#include <iostream>void work(int num) {while(num-- > 0) {std::cout << num << std::endl;}
}int main() {std::thread t(work, 5);t.join();return 0;
}

情况二:主线程没有join,出现core dump

#include <thread>
#include <iostream>void work(int num) {while(num-- > 0) {std::cout << num << std::endl;}
}int main() {std::thread t(work, 5);//t.join();return 0;
}

(2)lambda表达式

#include <thread>
#include <iostream>int main(int argc, char* argv[]){std::thread t([](int num){while (num-- > 0) {std::cout << num << std::endl;}}, 5);t.join();return 0;
}

(3)仿函数

#include <thread>
#include <iostream>
#include <unistd.h>class Demo {
public:void operator()(int num) {while(num-- > 0) {std::cout << num << std::endl;}}
};int main(int argc, char* argv[]) {std::thread t(Demo(), 5);t.join();return 0;
}

(4)静态成员函数

#include <thread>
#include <iostream>class Demo {
public:static void work(int num){while(num-- > 0) {std::cout << num << std::endl;}}
};int main(int argc, char* argv[]) {std::thread t(&Demo::work, 5);t.join();return 0;
}

(5)非静态成员函数

#include <thread>
#include <iostream>class Demo {
public:void work(int num){while(num-- > 0) {std::cout << num << std::endl;}}
};int main(int argc, char* argv[]) {Demo d;std::thread t(&Demo::work, &d, 5);t.join();return 0;
}
http://www.lryc.cn/news/214486.html

相关文章:

  • Distilling the Knowledge in a Neural Network学习笔记
  • JVM虚拟机:垃圾回收算法和垃圾回收器之间的关系
  • oracle sqlplus的使用 ,查询oracle实例名和服务名,查询oracle容器,切换oracle容器
  • golang工程——opentelemetry简介、架构、概念、追踪原理
  • Python 自动化(十六)静态文件处理
  • C#学习系列之密闭类、接口、结构和类
  • C++特殊类的设计
  • 量化交易Copula建模应对市场低迷
  • 美创科技位居IDC MarketScape:中国数据安全管理平台市场「领导者」类别
  • Go语言变量的使用
  • 在vitis中bit位赋值如何优化到一拍完成
  • 深度学习入门(二)之 简单手写数字识别实现
  • USART HMI串口屏+单片机通讯上手体验
  • Linux进程概念(1)
  • uniapp 查看安卓第三方插件抛出的异常
  • 美妆造型教培服务预约小程序的作用是什么
  • Pytorch常用函数
  • 如何利用python连接讯飞的星火大语言模型
  • 【Kubernetes 基本概念】Kubernetes 的架构和核心概念
  • Docker安装部署Elasticsearch+Kibana+IK分词器
  • PCL setCameraPosition 参数讲解
  • 有关YOLOV5在测试时,图片大小被调整的问题
  • 【机器学习】四、计算学习理论
  • spring解决后端显示时区的问题
  • 大模型冷思考:企业“可控”价值创造空间还有多少?
  • ctfshow-web入门37-52
  • 前端项目部署后,需要刷新页面才能看到更新内容
  • android 13 write javaBean error at *** 错误
  • Only fullscreen opaque activities can request orientation
  • 前端实验(一)单页面应用的创建