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

推荐订阅源

H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
Check Point Blog
Hacker News: Ask HN
Hacker News: Ask HN
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
WordPress大学
WordPress大学
P
Proofpoint News Feed
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 叶小钗
Cisco Talos Blog
Cisco Talos Blog
S
Schneier on Security
T
Threat Research - Cisco Blogs
腾讯CDC
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Hacker News
The Hacker News
Google DeepMind News
Google DeepMind News
Microsoft Security Blog
Microsoft Security Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
GbyAI
GbyAI
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Palo Alto Networks Blog
T
Tenable Blog
S
Secure Thoughts
T
Threatpost
V2EX - 技术
V2EX - 技术
大猫的无限游戏
大猫的无限游戏
Martin Fowler
Martin Fowler
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
罗磊的独立博客
P
Privacy & Cybersecurity Law Blog
Engineering at Meta
Engineering at Meta
小众软件
小众软件
Google DeepMind News
Google DeepMind News
N
News and Events Feed by Topic
Y
Y Combinator Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
L
Lohrmann on Cybersecurity
P
Privacy International News Feed
H
Heimdal Security Blog
量子位
B
Blog

Lei Mao's Log Book

2026 FIFA World Cup 备受嘲讽的会徽 Python Debugging Via VS Code In Docker Container Vargas Plateau Regional Park 徒步 Vargas Plateau Regional Park Apex 2026 FIFA World Cup 小组赛赛程 Retaining EXIF Metadata In GIMP San Francisquito Creek Joint Powers Authority 2025 Calendar Photo 麦当劳 The FIFA World Cup 套餐 Ardenwood Historic Farm 徒步 Ardenwood Historic Farm Synchronizations With TorchRec KeyedJaggedTensor Pacific Commons Linear Park 徒步 Pacific Commons Linear Park 2026 San Jose Half Marathon 竞赛 目标 Mountain View Shoreline Park 徒步 Mountain View Shoreline Park PyTorch AOTInductor Hybrid Lowering Carquinez Strait Regional Shoreline 徒步 Carquinez Strait Regional Shoreline PyTorch Triton Kernel Transparent Tracing and Compilation 脸庞 PyTorch Fake Export 2026 BRAIN Foundation 10K 竞赛 2026 Wild and Scenic Film Festival 参观 2026 Wild and Scenic Film Festival 系统工程程序员修 Bug FIFA 官方网站的语言 PyTorch Custom Operation 汉堡王 The Mandalorian and Grogu 套餐 Tilden Regional Parks Botanic Garden 参观 Tilden Regional Park Tilden Regional Parks Botanic Garden Tilden Regional Park 徒步 《寻秦记》电影版 ICML 2026 Area Chair Experience 2026 Foster City 5K Fun Run 竞赛 2026 年 3 月和 4 月该入手的模型手办 Docker Container GUI Display Using Wayland 马拉松破二 2026 Heart & Soles Run 5K 竞赛 How Is FARS, The Fully Automated Research System? 算计: 七天的死亡游戏 Lake Chabot Regional Park 徒步 Lake Chabot Regional Park 2023 年恐怖电影《感恩节》 2026 Airport Runway Run at San Carlos Airport 5K 竞赛 Page Table for Page-Locked Host Memory Don Edwards San Francisco Bay National Wildlife Refuge - Ravenswood 徒步 Don Edwards San Francisco Bay National Wildlife Refuge - Ravenswood 法外风云 PyTorch Graph Symbolic Integer Contra Costa Canal Regional Trail 徒步 Contra Costa Canal Regional Trail 娑婆诃 PyTorch Export 2026 Western Pacific 5K 竞赛 浮躁的科研和胡扯的自媒体 Connecting Logitech Devices On Linux 2026 Oakland Half Marathon 竞赛 Del Valle Regional Park 徒步 Del Valle Regional Park CUDA_LAUNCH_BLOCKING=1 踏切时间 Wildcat Canyon Regional Park 徒步 Wildcat Canyon Regional Park Credit Card Unauthorized Transaction While In Possession 莎拉的真伪人生 2026 Union City Superhero Fun Run 5K 竞赛 McLaughlin Eastshore State Park 徒步 McLaughlin Eastshore State Park Cloudflare Worker Proxy R2 Bucket Access Zorro 和 Batman Fix MacBook Pro Space Key Stuck Problem 2026 年 1 月和 2 月该入手的模型手办 2026 Brazen Victory 10K 竞赛 儿时的玩伴李峰 Marsh Creek Regional Trail 徒步 Marsh Creek Regional Trail Perfetto GPU Flow Artifacts 百万人推理 System Performance Optimizations QQ 幻想 2026 Brazen Bay Breeze 5K 竞赛 CUDA Shared Memory Bank Conflict-Free Vectorized Access Dota 闪电站出售 Mountain View Downtown 徒步 Mountain View Downtown 2025 年跑步总结 2026 Rotary Mission Ten Half Marathon 竞赛 狗的素质等于人的素质 CUDA Rendezvous Stream Pleasanton Ridge Regional Park 徒步 Pleasanton Ridge Regional Park Xfinity Internet 多年来的使用感受 Randomized SVD Don Castro Regional Recreation Area 徒步 Don Castro Regional Recreation Area 拖车公司的大汉们
C++ Latch and Barrier
2026-02-06 · via Lei Mao's Log Book

Introduction

Scheduling threads and synchronizing their execution is a common requirement in concurrent programming. In C++11, the std::condition_variable was introduced to facilitate thread synchronization. However, creating such mechanisms can be complex and error-prone. In C++20, two new synchronization primitives, std::latch and std::barrier, were introduced to simplify thread synchronization in certain scenarios.

In this blog post, I would like to demonstrate how to use create new implementations using std::latch and std::barrier to replace an existing producer-consumer model example implementation using std::condition_variable.

C++ Condition Variable

In my previous blog post “C++ Condition Variable”, I demonstrated how to use std::condition_variable introduced in C++11 to synchronize threads using the following producer-consumer model example.

wait_notify.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
std::cout << "Worker thread start" << std::endl;
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [] { return ready; });


std::cout << "Worker thread is processing data" << std::endl;
data += " after processing";


processed = true;
std::cout << "Worker thread signals data processing completed" << std::endl;



lk.unlock();


cv.notify_one();
}

void master_thread()
{
std::cout << "Master thread start" << std::endl;
data = "Example data";

{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "Master thread signals data ready for processing"
<< std::endl;
}


cv.notify_one();


{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [] { return processed; });
}
std::cout << "Back in master thread, data = " << data << std::endl;
}

int main()
{
std::thread worker(worker_thread), master(master_thread);


worker.join();
master.join();
}
1
2
3
4
5
6
7
8
$ g++ wait_notify.cpp -o wait_notify -std=c++11
$ ./wait_notify
Worker thread start
Master thread start
Master thread signals data ready for processing
Worker thread is processing data
Worker thread signals data processing completed
Back in master thread, data = Example data after processing

C++ Latch and Barrier

The above example works fine, but it requires careful management of mutexes, condition variables, and spurious wakeups, which is somewhat tedious and confusing. The same producer-consumer model example can be implemented more straightforwardly using the new synchronization primitives std::latch or std::barrier introduced in C++20.

The key difference between std::latch and std::barrier is that a latch is a one-time-use synchronization primitive, while a barrier can be reused multiple times. A latch is typically used when you want to wait for a set of threads to complete their tasks before proceeding, whereas a barrier is used when you want to synchronize a set of threads at multiple points in their execution.

C++ Latch

Compared to the implementation using std::condition_variable, the implementation using std::latch is much simpler and easier to understand.

latch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <chrono>
#include <iostream>
#include <latch>
#include <string>
#include <thread>

std::string data;
std::latch worker_latch(1);
std::latch master_latch(1);

void worker_thread()
{
std::cout << "Worker thread start" << std::endl;

worker_latch.wait();


std::cout << "Worker thread is processing data" << std::endl;
data += " after processing";


std::cout << "Worker thread signals data processing completed" << std::endl;
master_latch.count_down();
}

void master_thread()
{
std::cout << "Master thread start" << std::endl;
data = "Example data";

std::cout << "Master thread signals data ready for processing"
<< std::endl;
worker_latch.count_down();


master_latch.wait();
std::cout << "Back in master thread, data = " << data << std::endl;
}

int main()
{
std::thread worker(worker_thread), master(master_thread);


worker.join();
master.join();
}
1
2
3
4
5
6
7
8
$ g++ latch.cpp -o latch -std=c++20
$ ./latch
Worker thread start
Master thread start
Master thread signals data ready for processing
Worker thread is processing data
Worker thread signals data processing completed
Back in master thread, data = Example data after processing

C++ Barrier

Similarly, the same example could be implemented using std::barrier. Note that in this case, instead of using two latches, we can reuse a single barrier for synchronization between the master and worker threads.

barrier.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <barrier>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>

std::string data;
std::barrier sync_point(2);

void worker_thread()
{
std::cout << "Worker thread start" << std::endl;

sync_point.arrive_and_wait();


std::cout << "Worker thread is processing data" << std::endl;
data += " after processing";


std::cout << "Worker thread signals data processing completed" << std::endl;
sync_point.arrive_and_wait();
}

void master_thread()
{
std::cout << "Master thread start" << std::endl;
data = "Example data";

std::cout << "Master thread signals data ready for processing"
<< std::endl;
sync_point.arrive_and_wait();


sync_point.arrive_and_wait();
std::cout << "Back in master thread, data = " << data << std::endl;
}

int main()
{
std::thread worker(worker_thread), master(master_thread);


worker.join();
master.join();
}
1
2
3
4
5
6
7
8
$ g++ barrier.cpp -o barrier -std=c++20
$ ./barrier
Worker thread start
Master thread start
Master thread signals data ready for processing
Worker thread is processing data
Worker thread signals data processing completed
Back in master thread, data = Example data after processing

Conclusions

The std::latch and std::barrier synchronization primitives introduced in C++20 are important concepts for thread synchronization especially used in producer-consumer models. They provide a simpler and more intuitive way to manage thread synchronization compared to traditional methods using mutexes and condition variables.

References