并发支持库
第 32 章导读:线程、原子操作、锁、条件变量、信号量、latch/barrier、future 等组件如何为内存模型提供同步手段,以及读这些函数说明时要看哪几个元素。
本节要点
- 核心语言只定义线程间的先后关系(happens before 等)和"数据竞争是 UB",真正建立这些关系的手段全在第 32 章。
- 两个线程之间的写入是否可见,只能依据函数说明里的 Synchronization 元素判断;
sleep_for和yield明确不同步。 - "并发调用不引入数据竞争"只说明这些调用彼此安全,不提供任何同步。
- 违反 Preconditions(比如解锁不属于自己的互斥量)是 UB,实现通常不检查;Error conditions 则是有定义、以异常报告的失败。
核心语言缺的那一半#
#include <chrono>
#include <thread>
int data = 0;
int main() {
std::thread t([] { data = 1; });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
int r = data; // UB: 与 t 中的写构成数据竞争
(void)r;
t.join();
}主线程睡了 100 毫秒,t 几乎肯定早已写完,但这段程序仍然有数据竞争。按 [intro.races]/17,两个线程对同一对象的冲突访问(至少一个是写),只要彼此之间没有 happens before 关系,就是数据竞争,结果是 UB。时间上的先后不算数。用 -fsanitize=thread 运行,ThreadSanitizer 会报告 data race。
happens before 这类关系定义在 [intro.multithread],但核心语言本身没有任何建立它们的语法:没有创建线程的关键字,也没有内建的锁。能产生同步(synchronizes with,[intro.races]/6)的操作全部是第 32 章的库函数。把 int r = data; 挪到 t.join() 之后就对了,因为 [thread.thread.member]/4 规定线程执行完毕与 join() 的返回同步。
常见的同步来源:
std::thread的构造完成与线程函数开始执行同步,线程完成与join()返回同步([thread.threads]);- 原子操作的
memory_order决定一次 load/store 建立哪些关系([atomics.order]); - 互斥量的
unlock()与之后对同一互斥量的lock()同步([thread.mutex.requirements]); - 条件变量、信号量、latch、barrier、future 各自在函数说明里写明它们建立的关系。
本章的组成(¶1)#
¶1 只有一句话和一张表(表 154),列出各子条款和头文件:
| 子条款 | 内容 | 头文件 |
|---|---|---|
| [thread.req] | 通用要求:异常、native handle、超时、Cpp17Lockable 系列要求 | — |
| [thread.stoptoken] | stop_token、stop_source、stop_callback,C++26 的 inplace_stop_*、never_stop_token |
<stop_token> |
| [thread.threads] | thread、jthread、this_thread |
<thread> |
| [atomics] | memory_order、atomic<T>、atomic_ref<T>、atomic_flag、栅栏、等待与通知 |
<atomic>、<stdatomic.h> |
| [thread.mutex] | 互斥量、lock_guard/scoped_lock/unique_lock/shared_lock、std::lock、call_once |
<mutex>、<shared_mutex> |
| [thread.condition] | condition_variable、condition_variable_any |
<condition_variable> |
| [thread.sema] | counting_semaphore、binary_semaphore |
<semaphore> |
| [thread.coord] | latch、barrier |
<latch>、<barrier> |
| [futures] | promise、future、shared_future、packaged_task、async |
<future> |
| [saferecl] C++26 | RCU、hazard pointer | <rcu>、<hazard_pointer> |
读函数说明时看哪几个元素#
库条款里每个函数的说明分成若干元素(Effects、Returns 等),各自的法律效力由 [structure.specifications] ¶3 规定。读本章时最要紧的是下面三个。
Synchronization:线程间可见性的唯一依据#
[structure.specifications] ¶3.7 规定,Synchronization 元素给出适用于该函数的同步操作。本章的措辞有四种强度:
| 措辞 | 例子 | 能推出什么 |
|---|---|---|
| A synchronizes with B | 线程完成 → join() 返回;unlock() → 之后的 lock() |
A happens before B([intro.races]/7),A 之前的写对 B 之后的读可见 |
| A strongly happens before B | latch::count_down → 被它解除阻塞的调用返回([thread.latch.class] ¶9);semaphore::release → 观察到结果的 try_acquire([thread.sema.cnt] ¶10) |
比 happens before 更强([intro.races]/8),还约束 seq_cst 操作的全序([atomics.order]/4) |
| do not introduce data races | 并发调用同一个 latch 或 counting_semaphore 的成员函数 |
只保证这些调用彼此不构成数据竞争,不附带同步 |
| Synchronization: None | this_thread::yield、sleep_for、sleep_until([thread.thread.this]) |
明确不同步,上面的例子就是这种情况 |
第三行容易误读。"do not introduce data races" 说的是对象自身的内部状态可以并发访问,例如两个线程可以同时对一个 latch 调用成员函数。它不保证一个线程在调用之前写的普通变量,对另一个线程可见。要得到可见性,还得找一条 synchronizes with 或 happens before。
Preconditions:违反即 UB#
[structure.specifications] ¶3.4 规定,违反 Preconditions 是未定义行为。本章的前置条件大多与所有权有关:
- 调用
unlock()的线程必须持有这个互斥量([thread.mutex.requirements.mutex.general] ¶21); - 已经持有
std::mutex的线程不能再对它lock(); - 销毁
condition_variable时不能有线程还阻塞在它上面([thread.condition]); counting_semaphore::release不能让计数超过max()([thread.sema.cnt])。
实现通常不检查这些条件。macOS 上的 libc++ 对一个没人持有的 std::mutex 调用 unlock(),不报错也不终止,程序继续运行。
Error conditions:有定义的失败#
Error conditions 列出的是有定义的失败:函数抛出 system_error,其 code() 等于列出的某个 errc 值([thread.req.exception])。例如一个线程对代表自己的 std::thread 调用 join(),按 [thread.thread.member] 会抛出 resource_deadlock_would_occur,这是标准承诺的行为,不是 UB。
内存模型概念与库中的来源#
| 内存模型概念([intro.races]) | 本章中的来源 |
|---|---|
| synchronizes with(¶6) | release/acquire 原子操作([atomics.order]/2)、栅栏([atomics.fences])、各函数的 Synchronization 元素 |
| 修改顺序(¶4) | 每个原子对象各有一个;互斥量的 lock/unlock 为判断数据竞争也视作原子操作([thread.mutex.requirements.mutex.general] ¶4) |
| release sequence(¶5) | 原子读-改-写操作:fetch_add、exchange、成功的 compare_exchange_* |
| 单一全序 S | memory_order::seq_cst([atomics.order]/4) |
| 阻塞与前进保证([intro.progress]) | 非无锁的原子操作视为可能阻塞([atomics.lockfree]/4);各类 wait 函数 |
建议的阅读顺序:先 [thread.threads](开线程、join);再 [thread.mutex.requirements]、[thread.lock]、[thread.condition](基于锁的同步);然后 [atomics.order]、[atomics.types.generic]、[atomics.fences](原子操作与内存序);接着 [atomics.wait]、[thread.sema]、[thread.coord];最后 [thread.stoptoken] 与 jthread、[futures]、[saferecl]。
libc++(macOS,Clang 23)
- 线程、互斥量、条件变量直接包装 pthreads:
sizeof(std::mutex)为 64,sizeof(std::condition_variable)为 48,std::thread只存一个pthread_t,大小为 8。 atomic::wait、counting_semaphore、latch、barrier建立在 libc++ 自己的"自旋、退避、平台等待"框架上,见 [atomics.wait]。- 尚未提供:
atomic<shared_ptr<T>>、原子的fetch_max/fetch_min、constexpr原子操作、inplace_stop_token系列、<rcu>、<hazard_pointer>。
条款一览
- 32.1General 概述[thread.general]
- 32.2Requirements 要求[thread.req]完成
- 32.2.1Template parameter names 模板形参名[thread.req.paramname]
- 32.2.2Exceptions 异常[thread.req.exception]
- 32.2.3Native handles 原生句柄[thread.req.native]
- 32.2.4Timing specifications 计时规格[thread.req.timing]
- 32.2.5Requirements for Cpp17Lockable types Cpp17Lockable 类型的要求[thread.req.lockable]
- 32.2.5.1General 概述[thread.req.lockable.general]
- 32.2.5.2Cpp17BasicLockable requirements Cpp17BasicLockable 要求[thread.req.lockable.basic]
- 32.2.5.3Cpp17Lockable requirements Cpp17Lockable 要求[thread.req.lockable.req]
- 32.2.5.4Cpp17TimedLockable requirements Cpp17TimedLockable 要求[thread.req.lockable.timed]
- 32.2.5.5Cpp17SharedLockable requirements Cpp17SharedLockable 要求[thread.req.lockable.shared]
- 32.2.5.6Cpp17SharedTimedLockable requirements Cpp17SharedTimedLockable 要求[thread.req.lockable.shared.timed]
- 32.3Stop tokens 停止令牌[thread.stoptoken]完成
- 32.3.1Introduction 引言[thread.stoptoken.intro]
- 32.3.2Header <stop_token> synopsis 头文件 <stop_token> 概要[thread.stoptoken.syn]
- 32.3.3Stop token concepts 停止令牌概念[stoptoken.concepts]
- 32.3.4Class stop_token 类 stop_token[stoptoken]
- 32.3.5Class stop_source 类 stop_source[stopsource]
- 32.3.6Class template stop_callback 类模板 stop_callback[stopcallback]
- 32.3.7Class never_stop_token 类 never_stop_token[stoptoken.never]
- 32.3.8Class inplace_stop_token 类 inplace_stop_token[stoptoken.inplace]
- 32.3.9Class inplace_stop_source 类 inplace_stop_source[stopsource.inplace]
- 32.3.10Class template inplace_stop_callback 类模板 inplace_stop_callback[stopcallback.inplace]
- 32.4Threads 线程[thread.threads]完成
- 32.4.1General 概述[thread.threads.general]
- 32.4.2Header <thread> synopsis 头文件 <thread> 概要[thread.syn]
- 32.4.3Class thread 类 thread[thread.thread.class]
- 32.4.3.1General 概述[thread.thread.class.general]
- 32.4.3.2Thread attributes 线程属性[thread.attributes]
- 32.4.3.3Class thread::id 类 thread::id[thread.thread.id]
- 32.4.3.4Constructors 构造函数[thread.thread.constr]
- 32.4.3.5Destructor 析构函数[thread.thread.destr]
- 32.4.3.6Assignment 赋值[thread.thread.assign]
- 32.4.3.7Members 成员[thread.thread.member]
- 32.4.3.8Static members 静态成员[thread.thread.static]
- 32.4.3.9Specialized algorithms 特化的算法[thread.thread.algorithm]
- 32.4.4Class jthread 类 jthread[thread.jthread.class]
- 32.4.4.1General 概述[thread.jthread.class.general]
- 32.4.4.2Constructors, move, and assignment 构造、移动与赋值[thread.jthread.cons]
- 32.4.4.3Members 成员[thread.jthread.mem]
- 32.4.4.4Stop token handling 停止令牌处理[thread.jthread.stop]
- 32.4.4.5Specialized algorithms 特化的算法[thread.jthread.special]
- 32.4.4.6Static members 静态成员[thread.jthread.static]
- 32.4.5Namespace this_thread 命名空间 this_thread[thread.thread.this]
- 32.5Atomic operations 原子操作[atomics]完成
- 32.5.1General 概述[atomics.general]
- 32.5.2Header <atomic> synopsis 头文件 <atomic> 概要[atomics.syn]
- 32.5.3Type aliases 类型别名[atomics.alias]
- 32.5.4Order and consistency 顺序与一致性[atomics.order]完成
- 32.5.5Lock-free property 无锁性质[atomics.lockfree]完成
- 32.5.6Waiting and notifying 等待与通知[atomics.wait]完成
- 32.5.7Class template atomic_ref 类模板 atomic_ref[atomics.ref.generic]完成
- 32.5.7.1General 概述[atomics.ref.generic.general]
- 32.5.7.2Operations 操作[atomics.ref.ops]
- 32.5.7.3Specializations for integral types 整型的特化[atomics.ref.int]
- 32.5.7.4Specializations for floating-point types 浮点类型的特化[atomics.ref.float]
- 32.5.7.5Specialization for pointers 指针的特化[atomics.ref.pointer]
- 32.5.7.6Member operators common to integers and pointers to objects 整数与对象指针共有的成员运算符[atomics.ref.memop]
- 32.5.8Class template atomic 类模板 atomic[atomics.types.generic]完成
- 32.5.8.1General 概述[atomics.types.generic.general]
- 32.5.8.2Operations on atomic types 原子类型上的操作[atomics.types.operations]
- 32.5.8.3Specializations for integers 整数的特化[atomics.types.int]
- 32.5.8.4Specializations for floating-point types 浮点类型的特化[atomics.types.float]
- 32.5.8.5Partial specialization for pointers 指针的部分特化[atomics.types.pointer]
- 32.5.8.6Member operators common to integers and pointers to objects 整数与对象指针共有的成员运算符[atomics.types.memop]
- 32.5.8.7Partial specializations for smart pointers 智能指针的部分特化[util.smartptr.atomic]草稿
- 32.5.9Non-member functions 非成员函数[atomics.nonmembers]
- 32.5.10Flag type and operations 标志类型与操作[atomics.flag]完成
- 32.5.11Fences 栅栏[atomics.fences]完成
- 32.5.12C compatibility C 兼容性[stdatomic.h.syn]
- 32.6Mutual exclusion 互斥[thread.mutex]完成
- 32.6.1General 概述[thread.mutex.general]
- 32.6.2Header <mutex> synopsis 头文件 <mutex> 概要[mutex.syn]
- 32.6.3Header <shared_mutex> synopsis 头文件 <shared_mutex> 概要[shared.mutex.syn]
- 32.6.4Mutex requirements 互斥体要求[thread.mutex.requirements]完成
- 32.6.4.1General 概述[thread.mutex.requirements.general]
- 32.6.4.2Mutex types 互斥体类型[thread.mutex.requirements.mutex]
- 32.6.4.3Timed mutex types 定时互斥体类型[thread.timedmutex.requirements]
- 32.6.4.4Shared mutex types 共享互斥体类型[thread.sharedmutex.requirements]
- 32.6.4.5Shared timed mutex types 共享定时互斥体类型[thread.sharedtimedmutex.requirements]
- 32.6.5Locks 锁[thread.lock]完成
- 32.6.5.1General 概述[thread.lock.general]
- 32.6.5.2Class template lock_guard 类模板 lock_guard[thread.lock.guard]
- 32.6.5.3Class template scoped_lock 类模板 scoped_lock[thread.lock.scoped]
- 32.6.5.4Class template unique_lock 类模板 unique_lock[thread.lock.unique]
- 32.6.5.5Class template shared_lock 类模板 shared_lock[thread.lock.shared]
- 32.6.6Generic locking algorithms 通用加锁算法[thread.lock.algorithm]
- 32.6.7Call once 一次调用[thread.once]完成
- 32.7Condition variables 条件变量[thread.condition]完成
- 32.7.1General 概述[thread.condition.general]
- 32.7.2Header <condition_variable> synopsis 头文件 <condition_variable> 概要[condition.variable.syn]
- 32.7.3Non-member functions 非成员函数[thread.condition.nonmember]
- 32.7.4Class condition_variable 类 condition_variable[thread.condition.condvar]
- 32.7.5Class condition_variable_any 类 condition_variable_any[thread.condition.condvarany]
- 32.8Semaphore 信号量[thread.sema]完成
- 32.9Coordination types 协调类型[thread.coord]完成
- 32.10Futures future[futures]完成
- 32.10.1Overview 概览[futures.overview]
- 32.10.2Header <future> synopsis 头文件 <future> 概要[future.syn]
- 32.10.3Error handling 错误处理[futures.errors]
- 32.10.4Class future_error 类 future_error[futures.future.error]
- 32.10.5Shared state 共享状态[futures.state]
- 32.10.6Class template promise 类模板 promise[futures.promise]
- 32.10.7Class template future 类模板 future[futures.unique.future]
- 32.10.8Class template shared_future 类模板 shared_future[futures.shared.future]
- 32.10.9Function template async 函数模板 async[futures.async]
- 32.10.10Class template packaged_task 类模板 packaged_task[futures.task]
- 32.11Safe reclamation 安全回收[saferecl]草稿
- 32.11.1General 概述[saferecl.general]
- 32.11.2Read-copy update (RCU) 读-复制-更新(RCU)[saferecl.rcu]
- 32.11.3Hazard pointers 风险指针[saferecl.hp]