C++20 线程协调类:从入门到精通

文章目录

    • 1. 初识线程协调
    • 2. std::barrier:多线程同步的屏障
      • 2.1 核心函数
      • 2.2 示例代码
      • 2.3 高级用法
      • 2.4 适用场景
    • 3. std::latch:一次性同步原语
      • 3.1 核心函数
      • 3.2 示例代码
      • 3.3 高级用法
      • 3.4 适用场景
    • 4. std::counting_semaphore:可重用的同步原语
      • 4.1 核心函数
      • 4.2 示例代码
      • 4.3 高级用法
      • 4.4 适用场景
    • 5. 性能与优化
    • 6. 实际应用案例
      • 6.1 并行矩阵乘法
      • 6.2 线程池
    • 7. 总结

在多线程编程中,线程之间的协调是一个关键问题。C++20 引入了三种新的同步原语: std::barrierstd::latchstd::counting_semaphore,它们极大地简化了线程间的同步操作。本文将从入门到精通,逐步深入地介绍这三种同步原语的使用方法和适用场景。

1. 初识线程协调

在多线程编程中,线程协调是指控制多个线程的执行顺序,确保它们在特定的点上同步或互斥。常见的线程协调问题包括:

  • 同步执行:多个线程需要在某个点上同步,然后一起继续执行。
  • 资源限制:限制同时访问某个资源的线程数量。
  • 任务完成:等待多个线程完成任务后继续执行。

C++20 引入的三种同步原语正是为了解决这些问题而设计的。

2. std::barrier:多线程同步的屏障

std::barrier 是一种用于多线程同步的机制,它允许一组线程在某个点(称为屏障点)上同步。当线程到达屏障点时,它会被阻塞,直到所有线程都到达该点,然后所有线程同时继续执行。

2.1 核心函数

  • arrive_and_wait():线程到达屏障点并等待,直到所有线程都到达屏障点。
  • arrive_and_drop():线程到达屏障点,减少一个期待线程数,并重置屏障。

2.2 示例代码

以下代码展示了如何使用 std::barrier 来同步多个线程:

#include <iostream>
#include <thread>
#include <barrier>
#include <vector>void worker(std::barrier& barrier, int id) {std::cout << "Thread " << id << " is working.\n";std::this_thread::sleep_for(std::chrono::milliseconds(1000 * id));std::cout << "Thread " << id << " reached the barrier.\n";barrier.arrive_and_wait();
}int main() {const int num_threads = 3;std::barrier barrier(num_threads);std::vector<std::thread> threads;for (int i = 0; i < num_threads; ++i) {threads.emplace_back(worker, std::ref(barrier), i + 1);}for (auto& t : threads) {t.join();}std::cout << "All threads have finished.\n";return 0;
}

2.3 高级用法

std::barrier 支持一个可选的回调函数,当所有线程到达屏障点时,回调函数会被自动调用。这可以用于执行一些同步操作,例如更新状态或清理资源。

std::barrier barrier(num_threads, [](std::size_t) {std::cout << "All threads have reached the barrier. Executing callback.\n";
});

2.4 适用场景

  • 分阶段任务:适用于多线程分阶段任务,每个阶段结束后同步。
  • 并行算法:例如矩阵乘法等多阶段并行算法。

3. std::latch:一次性同步原语

std::latch 是一种一次性同步原语,用于确保一组线程在某个条件满足后继续执行。它类似于 std::counting_semaphore,但只能使用一次。

3.1 核心函数

  • count_down():减少计数器的值。
  • wait():阻塞线程,直到计数器减少到零。

3.2 示例代码

以下代码展示了如何使用 std::latch 等待多个线程完成任务:

#include <iostream>
#include <thread>
#include <latch>
#include <vector>void worker(std::latch& latch, int id) {std::cout << "Thread " << id << " is working.\n";std::this_thread::sleep_for(std::chrono::milliseconds(1000 * id));std::cout << "Thread " << id << " finished. Counting down latch.\n";latch.count_down();
}int main() {const int num_threads = 3;std::latch latch(num_threads);std::vector<std::thread> threads;for (int i = 0; i < num_threads; ++i) {threads.emplace_back(worker, std::ref(latch), i + 1);}latch.wait();std::cout << "All threads have finished.\n";for (auto& t : threads) {t.join();}return 0;
}

3.3 高级用法

std::latch 的计数器可以初始化为任意值,但一旦计数器减少到零,后续的 wait() 调用将立即返回,而不会阻塞。

3.4 适用场景

  • 一次性同步:适用于一次性同步,确保所有线程完成某个任务后继续。
  • 资源初始化:例如初始化资源或等待所有任务完成。

4. std::counting_semaphore:可重用的同步原语

std::counting_semaphore 是一种计数信号量,用于控制对共享资源的访问。它类似于 std::latch,但可以多次使用。

4.1 核心函数

  • acquire():减少信号量的计数,阻塞直到计数大于零。
  • release():增加信号量的计数。

4.2 示例代码

以下代码展示了如何使用 std::counting_semaphore 控制线程的执行:

#include <iostream>
#include <thread>
#include <semaphore>
#include <vector>void worker(std::counting_semaphore<>& sem, int id) {std::cout << "Thread " << id << " is waiting.\n";sem.acquire();std::cout << "Thread " << id << " is working.\n";std::this_thread::sleep_for(std::chrono::milliseconds(1000 * id));std::cout << "Thread " << id << " finished.\n";
}int main() {const int num_threads = 3;std::counting_semaphore<> sem(2); // 允许同时运行两个线程std::vector<std::thread> threads;for (int i = 0; i < num_threads; ++i) {threads.emplace_back(worker, std::ref(sem), i + 1);}for (auto& t : threads) {t.join();}return 0;
}

4.3 高级用法

std::counting_semaphore 的计数器可以初始化为任意值,且可以通过 try_acquire() 尝试非阻塞地获取信号量。

4.4 适用场景

  • 资源限制:适用于控制对共享资源的访问。
  • 线程池:例如限制同时运行的线程数量。

5. 性能与优化

虽然 std::barrierstd::latchstd::counting_semaphore 提供了强大的同步功能,但过度使用同步原语可能会导致性能问题。以下是一些优化建议:

  1. 减少同步点:尽量减少线程同步的次数,避免不必要的阻塞。
  2. 使用局部变量:尽量使用线程局部变量(thread_local),减少线程间的竞争。
  3. 避免死锁:确保线程同步的顺序一致,避免死锁。
  4. 使用无锁编程:在可能的情况下,使用无锁编程技术,减少同步开销。

6. 实际应用案例

6.1 并行矩阵乘法

以下代码展示了如何使用 std::barrier 实现并行矩阵乘法:

#include <iostream>
#include <vector>
#include <thread>
#include <barrier>void multiply(const std::vector<std::vector<int>>& A, const std::vector<std::vector<int>>& B, std::vector<std::vector<int>>& result, int row, int col, std::barrier& barrier) {for (size_t i = 0; i < A.size(); ++i) {result[row][col] += A[row][i] * B[i][col];}barrier.arrive_and_wait();
}int main() {const int size = 4;std::vector<std::vector<int>> A(size, std::vector<int>(size, 1));std::vector<std::vector<int>> B(size, std::vector<int>(size, 2));std::vector<std::vector<int>> result(size, std::vector<int>(size, 0));std::barrier barrier(size * size);std::vector<std::thread> threads;for (size_t i = 0; i < size; ++i) {for (size_t j = 0; j < size; ++j) {threads.emplace_back(multiply, std::ref(A), std::ref(B), std::ref(result), i, j, std::ref(barrier));}}for (auto& t : threads) {t.join();}for (const auto& row : result) {for (const auto& val : row) {std::cout << val << " ";}std::cout << "\n";}return 0;
}

6.2 线程池

以下代码展示了如何使用 std::counting_semaphore 实现一个简单的线程池:

#include <iostream>
#include <thread>
#include <semaphore>
#include <queue>
#include <functional>
#include <vector>class ThreadPool {
public:ThreadPool(size_t num_threads) : semaphore(num_threads) {for (size_t i = 0; i < num_threads; ++i) {threads.emplace_back([this] {while (true) {std::function<void()> task;{std::unique_lock<std::mutex> lock(queue_mutex);condition.wait(lock, [this] { return stop || !tasks.empty(); });if (stop && tasks.empty()) {return;}task = std::move(tasks.front());tasks.pop();}task();}});}}~ThreadPool() {{std::unique_lock<std::mutex> lock(queue_mutex);stop = true;}condition.notify_all();for (auto& t : threads) {t.join();}}template <class F, class... Args>auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> {using return_type = typename std::result_of<F(Args...)>::type;auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));std::future<return_type> res = task->get_future();{std::unique_lock<std::mutex> lock(queue_mutex);if (stop) {throw std::runtime_error("enqueue on stopped ThreadPool");}tasks.emplace([task]() { (*task)(); });}condition.notify_one();return res;}private:std::vector<std::thread> threads;std::queue<std::function<void()>> tasks;std::mutex queue_mutex;std::condition_variable condition;bool stop = false;std::counting_semaphore<> semaphore;
};int main() {ThreadPool pool(4);auto result1 = pool.enqueue([] { return 42; });auto result2 = pool.enqueue([] { return 43; });std::cout << "Result 1: " << result1.get() << "\n";std::cout << "Result 2: " << result2.get() << "\n";return 0;
}

7. 总结

C++20 引入的 std::barrierstd::latchstd::counting_semaphore 提供了强大的线程协调机制,简化了多线程编程中的同步操作。它们各具特色,适用于不同的场景:

  • std::barrier:适用于多线程分阶段任务,每个阶段结束后同步。
  • std::latch:适用于一次性同步,确保所有线程完成某个任务后继续。
  • std::counting_semaphore:适用于控制对共享资源的访问。

通过合理使用这些同步原语,可以显著提高代码的可读性和性能,同时减少死锁和竞态条件的可能性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/37799.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Linux网络】手动部署并测试内网穿透

&#x1f4e2;博客主页&#xff1a;https://blog.csdn.net/2301_779549673 &#x1f4e2;博客仓库&#xff1a;https://gitee.com/JohnKingW/linux_test/tree/master/lesson &#x1f4e2;欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; 如有错误敬请指正&#xff01; &…

MySQL中的锁机制:从全局锁到行级锁

目录 1. 锁的基本概念 2. 全局锁 2.1 全局锁的定义 2.2 全局锁的类型 2.3 全局锁的使用场景 2.4 全局锁的实现方式 2.5 全局锁的优缺点 2.6 全局锁的优化 3. 表级锁 3.1 表级锁的类型 3.2 表级锁的使用场景 3.3 表级锁的优缺点 4. 意向锁&#xff08;Intention Lo…

2025年渗透测试面试题总结- 某亭-安全研究员(题目+回答)

网络安全领域各种资源&#xff0c;学习文档&#xff0c;以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具&#xff0c;欢迎关注。 目录 一、SQL注入过滤单引号绕过方法 二、MySQL报错注入常用函数 三、报错注入绕WAF 四、MySQL写文件函数…

MacOS安装 nextcloud 的 Virtual File System

需求 在Mac上安装next cloud实现类似 OneDrive 那样&#xff0c;文件直接保存在服务器&#xff0c;需要再下载到本地。 方法 在 官网下载Download for desktop&#xff0c;注意要下对版本&#xff0c;千万别下 Mac OS默认的那个。 安装了登录在配置过程中千万不要设置任何同…

1.8 函数的连续性和间断点

1.连续的定义 2.间断点的定义 3.间断点的分类

Unity 云渲染本地部署方案

Unity Render Streaming 云渲染环境搭建 0.安装 Unity Render Streaming 实现原理: 服务器与客户端实现功能包括: 详细内容见官方文档&#xff1a; 官方文档: https://docs.unity3d.com/Packages/com.unity.renderstreaming3.1/manual/tutorial.html Unity 流送云渲染介绍: …

每日一题力扣3248.矩阵中的蛇c++

3248. 矩阵中的蛇 - 力扣&#xff08;LeetCode&#xff09; class Solution { public:int finalPositionOfSnake(int n, vector<string>& commands) {int i 0;int j 0;for (int k0;k<commands.size();k) {if (commands[k] "RIGHT")j;else if (comma…

本地基于Ollama部署的DeepSeek详细接口文档说明

前文&#xff0c;我们已经在本地基于Ollama部署好了DeepSeek大模型&#xff0c;并且已经告知过如何查看本地的API。为了避免网络安全问题&#xff0c;我们希望已经在本地调优的模型&#xff0c;能够嵌入到在本地的其他应用程序中&#xff0c;发挥本地DeepSeek的作用。因此需要知…

FPGA 以太网通信(三)

一、UDP协议 UDP&#xff08;User Datagram Protocol Protocol&#xff09;&#xff0c;即用户数据报协议&#xff0c;是一种面向无连接的传输层协议。UDP和TCP协议都属于传输层协议&#xff0c;在网络传输中同一 IP 服务器需要提供各种不同的服务&#xff0c;为了区别不同的服…

期刊分区表2025年名单下载(经济学、管理学)

2025年期刊分区表包括SCIE、SSCI、A&HCI、ESCI和OAJ&#xff0c;共设置了包括自然科学、社会科学和人文科学在内的21个大类 本次分享的是期刊分区表2025年名单经济学类、管理学类&#xff0c;一共7631025条 一、数据介绍 数据名称&#xff1a;期刊分区表2025年名单 数据…

如何在MCU工程中启用HardFault硬错误中断

文章目录 一、HardFault出现场景二、启动HardFault三、C代码示例 一、HardFault出现场景 HardFault&#xff08;硬故障&#xff09; 错误中断是 ARM Cortex-M 系列微控制器中一个较为严重的错误中断&#xff0c;一旦触发&#xff0c;表明系统遇到了无法由其他异常处理机制解决…

智能体开发革命:灵燕平台如何重塑企业AI应用生态

在AI技术深度渗透产业的今天&#xff0c;**灵燕智能体平台**以“全生命周期管理”为核心&#xff0c;为企业提供从智能体开发、协作到落地的闭环解决方案&#xff0c;开创了AI应用工业化生产的新模式。 三位一体的智能体开发体系 1. Agent Builder&#xff1a;零门槛构建专属…

机器学习之支持向量机(SVM)算法详解

文章目录 引言一、 什么是支持向量机&#xff08;SVM&#xff09;二、 SVM的基本原理三、数学推导1.线性可分情况2. 非线性可分情况3. 核函数 四、SVM的优缺点优点&#xff1a;缺点&#xff1a; 五、 应用场景六、 Python实现示例七、 总结 引言 支持向量机&#xff08;Suppor…

【C++进阶】深入探索类型转换

目录 一、C语言中的类型转换 1.1 隐式类型转换 1.2. 显式类型转换 1.3.C语言类型转换的局限性 二、C 类型转换四剑客 2.1 static_cast&#xff1a;静态类型转换&#xff08;编译期检查&#xff09; 2.2 dynamic_cast&#xff1a;动态类型转换&#xff08;运行时检查&…

机器学习之KL散度推导

机器学习之KL散度推导 预备知识 熵、交叉熵、条件熵 熵 (Entropy) 这一词最初来源于热力学。1948年&#xff0c;克劳德爱尔伍德香农将热力学中的熵引入信息论&#xff0c;所以也被称为香农熵 (Shannon entropy)、信息熵 (information entropy)。 对于具体熵的定义和用法推荐…

使用PlotNeuralNet绘制ResNet50模型

一、下载所需软件 1、下载MikTex 作用:将.tex文件转换为PDF文件 下载官网链接:Getting MiKTeX 2、下载Git 作用:将PlotNeuralNet库从GitHub上下载下来,在cmd使用命令行: git clone https://github.com/SamuraiBUPT/PlotNeuralNet-Windows.git 就可以将PlotNeuralNet…

10分钟打造专属AI助手:用ms-swift实现自我认知微调

想象一下&#xff0c;你是辛辛苦苦利用开源模型打造一个专属的AI产品助手。这个助手不仅能高效解答客户的问题&#xff0c;还能自豪地告诉大家&#xff1a;“我是某某打造的某某助手&#xff0c;代表着我们的品牌和价值观。” 然而&#xff0c;当前市面上的开源AI模型虽然技术先…

尝试使用tauri2+Django+React的项目

前言 使用Tauri2前端&#xff0c;本质是进程间的通信。并非前后端。 而想使用nw&#xff0c;先后端打包exe&#xff0c;再和前端打包成exe&#xff0c;并没有完成成功。 而笔者从Tauri中看到这种可能性。很有可能成功基于SeaORMMySQLTauri2ViteReact等的CRUD交互项目-CSDN博…

【JavaWeb学习Day27】

Tlias前端 员工管理 条件分页查询&#xff1a; 页面布局 搜索栏&#xff1a; <!-- 搜索栏 --><div class"container"><el-form :inline"true" :model"searchEmp" class"demo-form-inline"><el-form-item label…

Milvus WeightedRanker 对比 RRF 重排机制

省流:优先选择WeightedRanker 以rag为例,优先选择bm25全文检索,其次选择向量检索 Milvus混合搜索中的重排机制 Milvus通过hybrid_search() API启用混合搜索功能&#xff0c;结合复杂的重排策略来优化多个AnnSearchRequest实例的搜索结果。本主题涵盖了重排过程&#xff0c;…