Concurrency support library
A guide to chapter 32: how threads, atomic operations, locks, condition variables, semaphores, latches/barriers, futures and the rest provide the means of synchronization for the memory model, and which elements to look at when reading these function specifications.
Key points
- The core language defines only the ordering relations between threads (happens before and so on) and "a data race is UB"; the means of actually establishing those relations are all in chapter 32.
- Whether a write in one thread is visible to another can only be decided from the Synchronization element of the function specifications;
sleep_forandyieldexplicitly do not synchronize. - "Concurrent calls do not introduce data races" says only that those calls are safe with respect to each other; it provides no synchronization.
- Violating Preconditions (such as unlocking a mutex you do not own) is UB, and implementations usually do not check; Error conditions are defined failures reported by exceptions.
The half the core language is missing#
#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: a data race with the write in t
(void)r;
t.join();
}The main thread sleeps for 100 milliseconds, and t has almost certainly finished writing long before, but this program still has a data race. By [intro.races]/17, two conflicting accesses to the same object from two threads (at least one a write) form a data race unless there is a happens before relation between them, and the result is UB. Being earlier in time does not count. Run with -fsanitize=thread, ThreadSanitizer reports a data race.
Relations like happens before are defined in [intro.multithread], but the core language itself has no syntax to establish them: no keyword to create a thread, no built-in lock. The operations that produce synchronization (synchronizes with, [intro.races]/6) are all library functions in chapter 32. Moving int r = data; after t.join() makes it correct, because [thread.thread.member]/4 specifies that the completion of the thread synchronizes with the return from join().
Common sources of synchronization:
- the completion of the
std::threadconstructor synchronizes with the start of the thread function, and the completion of the thread synchronizes with the return fromjoin()([thread.threads]); - the
memory_orderof an atomic operation determines which relations a load or store establishes ([atomics.order]); - a mutex's
unlock()synchronizes with a subsequentlock()on the same mutex ([thread.mutex.requirements]); - condition variables, semaphores, latches, barriers and futures each state in their function specifications the relations they establish.
What the chapter contains (¶1)#
¶1 is a single sentence and a table (Table 154) listing the subclauses and headers:
| Subclause | Contents | Header |
|---|---|---|
| [thread.req] | General requirements: exceptions, native handles, timeouts, the Cpp17Lockable family of requirements | — |
| [thread.stoptoken] | stop_token, stop_source, stop_callback, C++26's inplace_stop_* and never_stop_token |
<stop_token> |
| [thread.threads] | thread, jthread, this_thread |
<thread> |
| [atomics] | memory_order, atomic<T>, atomic_ref<T>, atomic_flag, fences, waiting and notifying |
<atomic>, <stdatomic.h> |
| [thread.mutex] | Mutexes, 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 pointers | <rcu>, <hazard_pointer> |
Which elements to look at in a function specification#
Each function specification in the library clauses is divided into elements (Effects, Returns and so on), whose legal force is set by [structure.specifications] ¶3. When reading this chapter, the following three matter most.
Synchronization: the only basis for visibility between threads#
[structure.specifications] ¶3.7 specifies that the Synchronization element gives the synchronization operations applicable to the function. This chapter uses wording of four strengths:
| Wording | Example | What follows |
|---|---|---|
| A synchronizes with B | thread completion → join() returns; unlock() → a subsequent lock() |
A happens before B ([intro.races]/7); writes before A are visible to reads after B |
| A strongly happens before B | latch::count_down → return from the call it unblocks ([thread.latch.class] ¶9); semaphore::release → a try_acquire that observes the result ([thread.sema.cnt] ¶10) |
stronger than happens before ([intro.races]/8), also constraining the total order of seq_cst operations ([atomics.order]/4) |
| do not introduce data races | concurrent calls to member functions of the same latch or counting_semaphore |
guarantees only that these calls do not race with each other; no synchronization comes with it |
| Synchronization: None | this_thread::yield, sleep_for, sleep_until ([thread.thread.this]) |
explicitly no synchronization; the example above is this case |
The third row is easy to misread. "Do not introduce data races" means the object's own internal state can be accessed concurrently; for example, two threads can call member functions on one latch at the same time. It does not guarantee that an ordinary variable written by one thread before the call is visible to the other. For visibility you still need to find a synchronizes with or happens before.
Preconditions: violation is UB#
[structure.specifications] ¶3.4 specifies that violating Preconditions is undefined behavior. Most preconditions in this chapter have to do with ownership:
- the thread calling
unlock()must own the mutex ([thread.mutex.requirements.mutex.general] ¶21); - a thread that already owns a
std::mutexcannotlock()it again; - no thread may still be blocked on a
condition_variablewhen it is destroyed ([thread.condition]); counting_semaphore::releasemust not raise the count abovemax()([thread.sema.cnt]).
Implementations usually do not check these conditions. libc++ on macOS, when unlock() is called on a std::mutex nobody owns, neither reports an error nor terminates; the program keeps running.
Error conditions: defined failures#
Error conditions list defined failures: the function throws system_error whose code() equals one of the listed errc values ([thread.req.exception]). For example, a thread calling join() on the std::thread that represents itself throws resource_deadlock_would_occur per [thread.thread.member]; that is behavior the standard promises, not UB.
Memory model concepts and their sources in the library#
| Memory model concept ([intro.races]) | Source in this chapter |
|---|---|
| synchronizes with (¶6) | release/acquire atomic operations ([atomics.order]/2), fences ([atomics.fences]), the Synchronization element of each function |
| modification order (¶4) | each atomic object has one; mutex lock/unlock are also treated as atomic operations for the purpose of determining data races ([thread.mutex.requirements.mutex.general] ¶4) |
| release sequence (¶5) | atomic read-modify-write operations: fetch_add, exchange, successful compare_exchange_* |
| single total order S | memory_order::seq_cst ([atomics.order]/4) |
| blocking and progress guarantees ([intro.progress]) | atomic operations that are not lock-free are considered potentially blocking ([atomics.lockfree]/4); the various wait functions |
Suggested reading order: start with [thread.threads] (starting threads, joining); then [thread.mutex.requirements], [thread.lock], [thread.condition] (lock-based synchronization); then [atomics.order], [atomics.types.generic], [atomics.fences] (atomic operations and memory orders); next [atomics.wait], [thread.sema], [thread.coord]; and finally [thread.stoptoken] with jthread, [futures], [saferecl].
libc++ (macOS, Clang 23)
- Threads, mutexes and condition variables wrap pthreads directly:
sizeof(std::mutex)is 64,sizeof(std::condition_variable)is 48, andstd::threadstores just apthread_t, size 8. atomic::wait,counting_semaphore,latchandbarrierare built on libc++'s own "spin, back off, platform wait" framework; see [atomics.wait].- Not yet provided:
atomic<shared_ptr<T>>, atomicfetch_max/fetch_min,constexpratomic operations, theinplace_stop_tokenfamily,<rcu>,<hazard_pointer>.
Contents
- 32.1General[thread.general]
- 32.2Requirements[thread.req]done
- 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[thread.req.lockable]
- 32.2.5.1General[thread.req.lockable.general]
- 32.2.5.2Cpp17BasicLockable requirements[thread.req.lockable.basic]
- 32.2.5.3Cpp17Lockable requirements[thread.req.lockable.req]
- 32.2.5.4Cpp17TimedLockable requirements[thread.req.lockable.timed]
- 32.2.5.5Cpp17SharedLockable requirements[thread.req.lockable.shared]
- 32.2.5.6Cpp17SharedTimedLockable requirements[thread.req.lockable.shared.timed]
- 32.3Stop tokens[thread.stoptoken]done
- 32.3.1Introduction[thread.stoptoken.intro]
- 32.3.2Header <stop_token> synopsis[thread.stoptoken.syn]
- 32.3.3Stop token concepts[stoptoken.concepts]
- 32.3.4Class stop_token[stoptoken]
- 32.3.5Class stop_source[stopsource]
- 32.3.6Class template stop_callback[stopcallback]
- 32.3.7Class never_stop_token[stoptoken.never]
- 32.3.8Class inplace_stop_token[stoptoken.inplace]
- 32.3.9Class inplace_stop_source[stopsource.inplace]
- 32.3.10Class template inplace_stop_callback[stopcallback.inplace]
- 32.4Threads[thread.threads]done
- 32.4.1General[thread.threads.general]
- 32.4.2Header <thread> synopsis[thread.syn]
- 32.4.3Class 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.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[thread.jthread.class]
- 32.4.5Namespace this_thread[thread.thread.this]
- 32.5Atomic operations[atomics]done
- 32.5.1General[atomics.general]
- 32.5.2Header <atomic> synopsis[atomics.syn]
- 32.5.3Type aliases[atomics.alias]
- 32.5.4Order and consistency[atomics.order]done
- 32.5.5Lock-free property[atomics.lockfree]done
- 32.5.6Waiting and notifying[atomics.wait]done
- 32.5.7Class template atomic_ref[atomics.ref.generic]done
- 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[atomics.types.generic]done
- 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]draft
- 32.5.9Non-member functions[atomics.nonmembers]
- 32.5.10Flag type and operations[atomics.flag]done
- 32.5.11Fences[atomics.fences]done
- 32.5.12C compatibility[stdatomic.h.syn]
- 32.6Mutual exclusion[thread.mutex]done
- 32.6.1General[thread.mutex.general]
- 32.6.2Header <mutex> synopsis[mutex.syn]
- 32.6.3Header <shared_mutex> synopsis[shared.mutex.syn]
- 32.6.4Mutex requirements[thread.mutex.requirements]done
- 32.6.5Locks[thread.lock]done
- 32.6.6Generic locking algorithms[thread.lock.algorithm]
- 32.6.7Call once[thread.once]done
- 32.7Condition variables[thread.condition]done
- 32.8Semaphore[thread.sema]done
- 32.9Coordination types[thread.coord]done
- 32.10Futures[futures]done
- 32.10.1Overview[futures.overview]
- 32.10.2Header <future> synopsis[future.syn]
- 32.10.3Error handling[futures.errors]
- 32.10.4Class future_error[futures.future.error]
- 32.10.5Shared state[futures.state]
- 32.10.6Class template promise[futures.promise]
- 32.10.7Class template future[futures.unique.future]
- 32.10.8Class template shared_future[futures.shared.future]
- 32.10.9Function template async[futures.async]
- 32.10.10Class template packaged_task[futures.task]
- 32.11Safe reclamation[saferecl]draft
- 32.11.1General[saferecl.general]
- 32.11.2Read-copy update (RCU)[saferecl.rcu]
- 32.11.3Hazard pointers[saferecl.hp]