C++11/std::thread – 线程管理join/detach
原创文章,作者:StubbornHuang,如若转载,请注明出处:《C++11/std::thread – 线程管理join/detach》https://www.stubbornhuang.com/776/
1 join方法
代码示例:
#include <iostream>
#include <thread>
void HelloWorld()
{
std::cout << "hello world" << std::endl;
}
int main()
{
std::thread helloWorldThread(HelloWorld);
helloWorldThread.join();
getchar();
return 0;
}
在上述代码中,线程函数HelloWorld将会被子线程helloWorldThread启动,并运行在该线程中,而join函数会阻塞线程,直到线程函数执行完毕,如果线程函数有返回值,那么返回值将会被忽略。
2 detach方法
如果我们不想线程被阻塞怎么办?使用detach方式,但是风险很高,你可以联想C++的野指针。
在下列代码中,线程函数HelloWorld将会被子线程helloWorldThread启动,并运行在该线程中,detach方法会将线程与线程对象分离,让子线程作为后台线程执行,当前的线程也不会被阻塞。但是,线程detach之后无法与当前线程取得任何联系,也就是说detach之后无法使用join等待线程执行完成,因为线程detach之后何时执行完毕取决于其函数体内的运算逻辑。
代码示例:
#include <iostream>
#include <thread>
void HelloWorld()
{
std::cout << "hello world" << std::endl;
}
int main()
{
std::thread helloWorldThread(HelloWorld);
helloWorldThread.detach();
// do other things 马上可以做其他事情,不会被阻塞
getchar();
return 0;
}
当前分类随机文章推荐
- C++11 - 基于无锁队列的单生产者单消费者模型
- C++11/std::shared_ptr - 循环引用问题
- C++ - queue存储动态指针时正确释放内存
- C++ - vector存储动态指针时正确释放内存
- C++ - std::map - 存储动态指针时正确释放内存
- C++11 - std::function简要介绍以及可包装函数的几种形式总结
- C++11 - 父类与子类相互包含的时候该如何正确的使用智能指针,防止循环引用
- C++ - 控制台程序在控制台窗口可变参数格式化带颜色输出日志信息
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error'
- C++读取Shp文件并将Shp转化为DXF
全站随机文章推荐
- Eigen踩坑1:Matrix的transpose(矩阵转置)计算之后不能赋值给自身
- Duilib - 颜色属性的设置
- VPS - 使用XShell连接VPS
- OpenCV - 打开摄像头并对摄像头获取的每一帧图像进行Canny算子边缘化提取操作
- 资源分享 - 《Linux命令行大全》.((美)William E.shotts,Jr)中文pdf下载
- C++读取Shp文件并将Shp转化为DXF
- 资源分享 - Fundamentals of Computer Graphics, Third Edition高清英文PDF下载
- WordPress - 纯代码在文章内容末尾添加当前文章同一分类下的随机推荐文章
- 工具网站推荐 - 获取本机外网IP
- WordPress - 利用Revolvermaps在首页实时显示访客3D地球