C++11/std::thread – 线程管理join/detach
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++11/std::thread – 线程管理join/detach
原文链接:https://www.stubbornhuang.com/776/
发布于:2020年04月01日 11:47:27
修改于:2020年04月01日 11:47:27
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;
}
当前分类随机文章推荐
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error' 阅读2590次,点赞1次
- C++STL容器 – std::vector容器修改、元素操作总结 push_back,emplace_back,emplace,insert,erase,pop_back,clear,resize,swap 阅读1041次,点赞1次
- C++ - Windows/Linux生成uuid(通用唯一识别码) 阅读1926次,点赞2次
- C++ - Jni中的GetByteArrayElements和GetByteArrayRegion的区别和使用示例 阅读3122次,点赞0次
- C++ - 对字符串和图片进行base64编解码 阅读320次,点赞0次
- C++ - std::string与std::wstring相互转换 阅读1970次,点赞0次
- C++ - 阿拉伯数字字符串转换为中文读法的中文字符串,支持小数点 阅读1343次,点赞0次
- C++11 - 封装std::thread,增加子线程启动、暂停、唤起、停止功能 阅读4828次,点赞7次
- C++ - 函数返回多个返回值的方法总结 阅读1963次,点赞0次
- C++ – UTF8编码下的全角字符转半角字符 阅读1822次,点赞0次
全站随机文章推荐
- Google Adsense - 使用招商银行电汇收款 阅读1260次,点赞2次
- 资源分享 - Light & Skin Interactions - Simulations for Computer Graphics Applications 英文高清PDF下载 阅读1468次,点赞0次
- 资源分享 - Video Game Optimization 英文高清PDF下载 阅读1383次,点赞0次
- 资源分享 - Mathematics for 3D Game Programming and Computer Graphics, Second Edition 英文高清PDF下载 阅读2718次,点赞0次
- Python - 解决skvideo库的Cannot find installation of real FFmpeg (which comes with ffprobe)问题 阅读183次,点赞0次
- 资源分享 - An Introduction to Computational Fluid Dynamics - The Finite Volume Method (First Edition)英文高清PDF下载 阅读415次,点赞0次
- 资源分享 - Game Programming Gems 8 英文高清PDF下载 阅读2904次,点赞0次
- Duilib - 点击按钮弹出模态对话框 阅读2041次,点赞0次
- Python - opencv-python统计一个文件夹以及所有子文件夹下所有视频的帧率和帧数 阅读359次,点赞0次
- C++ - 控制台程序在控制台窗口可变参数格式化带颜色输出日志信息 阅读3287次,点赞0次
评论
169