惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
Security Latest
Security Latest
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
Cybersecurity and Infrastructure Security Agency CISA
Cloudbric
Cloudbric
T
Threat Research - Cisco Blogs
大猫的无限游戏
大猫的无限游戏
C
CXSECURITY Database RSS Feed - CXSecurity.com
阮一峰的网络日志
阮一峰的网络日志
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
雷峰网
雷峰网
C
Cisco Blogs
V
Vulnerabilities – Threatpost
S
Security Archives - TechRepublic
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
J
Java Code Geeks
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Know Your Adversary
Know Your Adversary
博客园 - 叶小钗
腾讯CDC
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Privacy International News Feed
P
Palo Alto Networks Blog
博客园_首页
V
V2EX
WordPress大学
WordPress大学
Schneier on Security
Schneier on Security
月光博客
月光博客
博客园 - 司徒正美
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 【当耐特】
The Cloudflare Blog
罗磊的独立博客
美团技术团队
N
News | PayPal Newsroom
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Last Week in AI
Last Week in AI
K
Kaspersky official blog
Google Online Security Blog
Google Online Security Blog
S
SegmentFault 最新的问题
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog

又见苍岚

COLMAP PatchMatch Stereo 算法详解 事件驱动的状态机框架:从理论到工程实践 Git 在国内网络环境下无法 Push 的排查与修复 —— 配置 Clash 代理 分段五次多项式插值原理详解 路径插值方法深度对比研究 Claude Code 使用指南 OpenClaw 记忆管理与技能创建指南 CBS(Conflict-Based Search)算法详解 A* 算法及其变种详解 OpenClaw 配置多 Agents Windows Powershell 无法加载文件,因为在此系统上禁止运行脚本问题的解决方案 MaxClaw 安装流程 大模型 AI 名词介绍 AList 网盘聚合工具简介 Protobuf 简介与测试 Claude Code 简介以及 GLM 4.7 模型接入 Github 歌词下载工具 163MusicLyrics Python __getattr__ 懒加载 Python TypedDict 机器人仿真平台 Gazebo 安装记录 机器人仿真平台 Gazebo 简介 多机器人路径规划问题(Multi-Agent Path Finding, MAPF)简介 Python exifread 读取修改过的 jpeg 信息错误问题修复 3D 坐标系变换的理解 3D 旋转矩阵基本概念 MongoDB Compass 介绍 Python 环境管理工具 uv Flutter 开发指南 Snipaste 安装下载与黑屏问题解决方案 全局路径规划算法记录 2025 Python 版本性能测试 Flutter Hello World Flutter 安装环境配置 Ubuntu VMware 硬盘扩容后 SMBus Host controller not enabled 报错问题解决 Python NetworkX 教程 Docker GPU 报错 - Failed to initialize NVML Unknown Error 解决方案 Python matplotlib 图表绘制 cuda-toolkit 安装替代 Cuda 与 Cudnn Jinja2 Python 利用 docxtpl 和 Jinja2 生成基于模板的 Word 文档 Docker 实现 CPU 核心隔离 LoFTR 基于 Transformer 的特征提取匹配算法 OmniGlue 特征匹配 SuperGlue 使用图神经网络学习特征匹配 Ubuntu 下将 xlsx 文件按照 sheet 转换为 图片 Python 使用 SQLAlchemy Python FastAPI 教程 openwrt 软路由配置安装 Nav2 地图文件(PGM/YAML)规范标准 3D OBJ 模型转换为 glb 瓦片格式 Python 源码 Redis 数据库介绍 Ubuntu 22.04 内核自动升级导致 MongoDB 7.0.12 错误记录 ubuntu 20.04 安装 ROS Noetic ubuntu 18.04 安装 ROS Melodic VMware Workstation Pro 个人免费版下载、安装、使用指南 Hybrid A-star 路径规划 Reeds-Shepp 曲线 Dubins 曲线 Linux kvm 虚拟机网络不通的问题解决方法 Ubuntu 自动内存清理 BiliBili 缓存视频转 mp4 Python 求解线性规划 3D Gaussian Splatting 官方源码实践记录 ImageMagick 教程 Ubuntu 22.04 安装 Colmap 对数几率 odds Ubuntu nmcli 网络管理工具使用指南 SuperPoint 自监督深度学习特征点提取 SyncTV Music Tag Web 在线音乐信息整理工具 ncm 格式转 mp3 MusicBrainz 音乐元数据百科数据库 Ubuntu 网络流量监控工具 私人云音乐平台 Navidrome 入门 手眼标定 四元数(Quaternions) OHTTPS 实现免费自动 https 证书申请、更新、部署 ubuntu 22.04 安装 CloudCompare 单机 KVM 虚拟机冷迁移 Ubuntu 22.04 使用 mdadm 实现软 raid 小鱼 一键安装 ROS-humble Fluid -46- 基于 Simpletex API 构建公式识别页面 公式识别 API 简介 -- Simpletex 使用 Python web 部署库 waitress 3D Gaussian Splatting for Real-Time Radiance Field Rendering Ubuntu Swap 简介与空间扩展 Ubuntu 24.04 安装 forticlient Clash Verge 使用 MongoDB 7.0.17 集群 Docker 构建源码 Error code - 2013. Lost connection to MySQL server during query 问题解决 Python 日志记录库 loguru 使用指北 Python 实现 Web 日志查看服务 MySQL LOAD DATA LOCAL INFILE 极速数据加载 Image size exceeds limit of 89478485 pixels 解决方案 Docker 使用 NVIDIA GPU 驱动错误解决 阿里云 docker 镜像仓库 Ubuntu中没有wired connected的解决方案 MinIO 简介 subconverter 代理订阅格式转换 修复 node –openssl-legacy-provider is not allowed in NODE_OPTIONS 错误
C++ 线程操作
Yiwei Zhang · 2023-03-17 · via 又见苍岚

线程也叫轻量级进程,通常一个进程包含若干个线程。线程可以利用进程所拥有的资源。 本文记录 C++ 操作线程的方法。

并发

两个或者多个独立的活动同时进行的现象称为并发。并发可以简单的认为,可以理解成多个应用程序同时运行。在单核CPU中,并发实际上是一种假象,进程之间实际上是按照一定的分配算法轮流使用CPU。

并发的实现主要有两种方式:

  1. 多进程实现并发
  2. 单个进程,多个线程实现并发,就是一个主线程多个子线实现。

thread

C++ 11 之后添加了新的标准线程库 std::thread ,用于线程控制,std::thread<thread> 头文件中声明,因此使用 std::thread 时需要包含 在 <thread> 头文件。

std::thread 默认构造函数,创建一个空的 std::thread 执行对象。

1
2
#include<thread>
std::thread thread_object(callable)

一个可调用对象可以是以下三个中的任何一个:

  • 函数指针
  • 函数对象
  • lambda 表达式

创建线程

不带参的方式创建线程

不带参数的普通函数作为线程处理函数。

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
#include<thread>
using namespace std;
void print(){
cout<<"子线程在运行。。。"<<endl;
}
int main(){
//创建线程
thread t1(print);//print为线程处理函数
cout<<"主线程。。。"<<endl;
return 0;
}

通过类和对象创建线程

利用类中的仿函数作为线程处理函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
#include<thread>
using namespace std;
class A{
//STL 仿函数 类名模仿函数的行为
void operator()(){
cout<<"子线程..."<<endl;
}
};
int main(){
//正常写法1 对象充当线程处理函数
A a;
thread t1(a);
t1.join();

//写法2
// thread t1((A()));
// t1.join();

cout<<"主线程..."<<endl;
}

通过Lambda表达式创建线程

Lambda 表达式简单地说,就是将函数定义和调用放在一处实现。

1
2
3
4
5
6
7
8
#include<iostream>
#include<thread>
using namespace std;
int main(){
thread t1([]{cout<<"子线程调用..."<<endl;});
t1.join();
cout<<"主线程..."<<endl;
}

带参的方式创建线程

将带参数的函数作为线程处理函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<thread>
using namespace std;
void p1(int &n){
cout<<"子线程"<<n<<endl;
n++;
}
int main(){
int n=0;
thread t3(p1,std::ref(n));//ref用于包装引用传值
t3.join();
thread t31(p1,std::ref(n));
t31.join();
cout<<"主线程..."<<endl;
}

当有多个参数时可以直接接在线程的构造函数参数中,他会在后台默默运行

如果测试时设置了断点发现测试日志没有成功输出,可能是子线程还没有开始运转,可以加个 while(1){;} 再观察结果。

智能指针的方式创建线程

就是以智能指针为参数的函数作为线程处理函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void p2(unique_ptr<int> ptr){
cout<<"子线程:"<<ptr.get()<<endl;
cout<<"子线程id: "<<this_thread::get_id()<<endl;//get_id函数获取线程id
}

int main(){
//智能指针为参数的线程处理函数
int *p=new int(12);
cout<<*p<<endl;//12
unique_ptr<int> ptr(new int(1000));
cout<<"主线程:"<<ptr.get()<<endl;//ptr.get() 获取智能指针的地址
thread t4(p2,move(ptr));
t4.join();
cout<<"主线程id: "<<this_thread::get_id()<<endl;
cout<<"主线程..."<<ptr.get()<<endl;//0000000 因为上面的语句将智能指针移动到p3中去,子线程结束后,智能指针自动释放啦。
}

类的成员函数创建线程

将类的成员函数作为线程处理函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class B{
public:
void p3(int &num){
num=1100;
cout<<"子线程id:"<<this_thread::get_id()<<endl;
}
};
int main(){
//类的成员函数充当线程处理函数
B b;
int num=10;
//需要告诉是哪一个对象的成员函数
thread t5(&B::p3,b,ref(num));//注意创建thread类对象的方式
t5.join();
cout<<"主线程id: "<<this_thread::get_id()<<endl;
}

使用方法

线程运行函数

创建线程:调用 thread 类去调用一个线程的对象,添加处理函数作为线程的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
#include<thread>
using namespace std;
void print(){
cout<<"子线程在运行。。。"<<endl;
}
int main(){
//创建线程
thread t1(print);//print为线程处理函数
cout<<"主线程。。。"<<endl;
return 0;
}

子线程可能正在运行时主线程已经退出了,可能会报出异常退出的错误,这就需要将线程的调度整合起来。

join( )

可以利用 join 函数加入,汇合线程,阻塞主线程。添加以后等线程运行结束之后才运行主线程。

注意: 一个线程只能 join 一次,不能重复。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<thread>
#include<windows.h>
using namespace std;
//线程处理函数
void print(){
Sleep(2000);//休眠2s
cout<<"子线程在运行..."<<endl;
}
int main(){
//创建线程
thread t1(print);
t1.join();//阻塞 ,添加以后等线程运行结束之后才运行主线程
cout<<"主线程..."<<endl;
return 0;
}

输出

1
2
子线程在运行。。。
主线程。。。

detach( )

detach( ) 函数用于打破主线程和子线程之间的依赖关系,将子线程和主线程之间进行分离,不影响。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<thread>
#include<windows.h>
using namespace std;
//线程处理函数
void print()
{
Sleep(2000);//休眠2s
cout << "子线程在运行..." << endl;
}
int main()
{
//创建线程
thread t1(print);
t1.detach();//子线程与主线程分离
cout << "主线程..." << endl;
return 0;
}

输出

1
主线程...

joinable( )

joinable( ) 函数是一个布尔类型的函数,他会返回一个布尔值来表示当前的线程是否是可执行线程(能被 join 或者 detach)

因为相同的线程不能 join 两次,也不能 join 完再 detach, 同理也不能 detach, 所以 joinable 函数就是用来判断当前这个线程是否可以 join 的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<thread>
using namespace std;
void print(){
cout<<"子线程在运行。。。"<<endl;
}
int main(){
thread t1(print);
t1.join();
cout<<"主线程..."<<endl;
if(t1.joinable())
cout<<"能join"<<endl;
else
cout<<"不能进行join"<<endl;
return 0;
}

输出

1
2
3
子线程在运行。。。
主线程...
不能进行join

get_id()

获取当前线程 id

1
std::this_thread.get_id()

参考资料

文章链接:
https://www.zywvvd.com/notes/coding/cpp/cpp-thread/cpp-thread/