C++ Concurrency: std::thread vs. Lightweight Fibers, Channel, & Abseil Mutex#
This guide covers the architectural differences and usage patterns between OS kernel threads (std::thread / std::jthread) and user-space lightweight threads (thread::Fiber), CSP message passing (thread::Channel<T> & thread::Select) and how it directly inspired the Go programming language, and synchronization with compile-time thread safety verification using open-source Abseil (abseil-cpp) primitives (absl::Mutex and ABSL_GUARDED_BY).
1. OS Kernel Threads (std::thread) vs. User-Space Lightweight Threads (Fibers)#
In modern high-performance servers, concurrency models generally fall into two categories: 1:1 OS kernel threads and M:N user-space lightweight threads (Fibers).
[1:1 Model: std::thread] [M:N Model: User-Space Fibers / Go Goroutines]
std::thread 1 std::thread 2 Fiber 1 Fiber 2 Fiber 3 ... Fiber 10,000
│ │ \ │ / /
─────┼──────────────┼───── (User/Kernel) ──┴─────────┼─────────┴──────────────┘
▼ ▼ [User-Space M:N Scheduler]
[OS Kernel Thread] [OS Kernel Thread] │ │
│ │ ─────────┼───────────────┼───── (User/Kernel)
[CPU Core 1] [CPU Core 2] ▼ ▼
[OS Worker Thread 1] [OS Worker Thread 2]1. std::thread / std::jthread (1:1 OS Kernel Threads)#
Each instance of C++11 std::thread (or C++20 std::jthread) maps 1:1 to a native operating system kernel thread (such as a Linux pthread).
- Strengths: The OS kernel scheduler preemptively time-slices threads across CPU cores, ensuring that a single CPU-bound loop cannot starve other threads.
- Limitations in High-Concurrency I/O Servers:
- Heavy Stack Footprint: Each OS thread reserves a fixed virtual stack (typically 8 MB by default on Linux, or hundreds of KB at minimum). Spawning tens of thousands of concurrent threads quickly exhausts memory.
- Expensive Creation & Destruction: Creating or destroying an OS thread requires kernel system calls (
clone()). - Costly Context Switching: When an OS thread blocks on network I/O or a contended lock, transitioning from user mode to kernel mode, saving registers, running the kernel scheduler, and polluting CPU caches/TLBs takes several microseconds ($1\sim 10,\mu\text{s}$).
2. User-Space Lightweight Threads (Fibers)#
To scale to tens of thousands of concurrent requests without the overhead of kernel threads, large-scale C++ systems use M:N user-space lightweight threads (Fibers), such as Boost’s boost::fibers::fiber, Meta’s folly::fibers, or open-source Abseil Gloop’s thread::Fiber: following the same M:N design as Go’s Goroutines (G-M-P scheduler).
- How M:N Cooperative Scheduling Works:
- A small pool of OS worker threads ($N$, typically matching CPU core count) runs a user-space scheduler that multiplexes thousands of lightweight fibers ($M$).
- When Fiber A waits on an asynchronous RPC or a fiber-aware synchronization primitive (
absl::Mutex, etc.), it does not block the underlying OS kernel thread. - Instead, the user-space scheduler swaps CPU registers (stack pointer
RSP, instruction pointerRIP, and callee-saved registers) to a ready Fiber B entirely in user space in $10\sim 30,\text{ns}$, without a single kernel system call.
3. Comparing Four Concurrency Execution Models#
| Dimension | std::thread / std::jthread | User-Space Fiber | C++20 Coroutines (co_await) | Go goroutine |
|---|---|---|---|---|
| Scheduler | OS Kernel (1:1 preemptive) | User-Space Runtime (M:N cooperative) | User-Space (stackless state machine) | Go Runtime (M:N hybrid cooperative/preemptive) |
| Dedicated Call Stack | ✅ Yes (multi-MB fixed stack) | ✅ Yes (Stackful, lightweight stack) | ❌ No (Stackless, heap-allocated coroutine frame) | ✅ Yes (2 KB initial stack, grows/shrinks dynamically) |
| Context Switch Cost | High ($1\sim 10,\mu\text{s}$, kernel trap) | Very Low ($10\sim 30,\text{ns}$, user-space register swap) | Extremely Low (a few $\text{ns}$, indirect function call) | Very Low (tens of $\text{ns}$ in user space) |
| Programming Model | Standard synchronous code | Standard synchronous code (can yield deep inside nested call stacks) | Requires viral Task<T> return types and co_await at every layer (Function Coloring Problem) | Standard synchronous code (go f()) |
| Primary Use Case | Worker pools, long-running CPU-intensive tasks | High-throughput RPC servers, high-fanout sub-tasks | Memory-constrained async I/O pipelines | All concurrency in Go |
Why Stackful Fibers Avoid the “Function Coloring Problem” of C++20 Stackless Coroutines: Because C++20
co_awaitcoroutines are stackless, a coroutine can only suspend its direct frame; in a call chainA() -> B() -> C(), ifC()needs to suspend,A,B, andCmust all be rewritten to return coroutine types and useco_await. Because Fibers are stackful (each owns a contiguous call stack), any regular synchronous C++ function deep in a call stack can yield execution and resume seamlessly.
2. How to Use std::thread / std::jthread and Fibers#
1. Standard std::thread and C++20 std::jthread#
The most critical lifecycle rule of std::thread is that you must call either join() or detach() before the std::thread object is destroyed (~thread()). If neither is called when a std::thread goes out of scope, its destructor immediately calls std::terminate(), crashing the entire process.
C++20 introduced std::jthread (Joining Thread), which applies RAII by automatically requesting stop and calling join() in its destructor, eliminating accidental std::terminate() crashes.
#include <iostream>
#include <memory>
#include <thread>
#include <utility>
void RunStandardThreads() {
int result_a = 0;
// 1. C++11 std::thread: passes a lambda; MUST manually call join() before scope exit!
std::thread t1([&result_a]() {
result_a = 42;
});
// 2. Passing move-only objects (std::unique_ptr) into a thread via C++14 init-capture + std::move
auto payload = std::make_unique<int>(100);
std::jthread t2([ptr = std::move(payload)]() {
std::cout << "Owned payload inside jthread: " << *ptr << "\n";
});
t1.join(); // Wait for t1 to finish (omitting this triggers std::terminate in ~thread()!)
// t2 is a std::jthread, so ~jthread() automatically joins at the end of the scope.
// Because t1 wrote to result_a by reference, we read result_a only after t1.join() completes.
std::cout << "result_a = " << result_a << "\n";
}Why
detach()Is Almost Always an Anti-Pattern: Callingt.detach()relinquishes control over when the thread finishes. If a detached thread references local stack variables,this, or static objects destroyed duringmain()shutdown, it causes Use-After-Free (dangling reference) crashes. Always follow Structured Concurrency: every spawned thread or fiber should be joined before its parent scope exits.
2. Two Core Usage Patterns for User-Space Fibers#
User-space fiber libraries (such as Boost.Fiber or Gloop thread::Fiber) mirror the ergonomics of std::thread while supporting two primary patterns: single fiber spawn/join and structured task bundles (WaitGroups).
Pattern A: Spawning and Joining a Single Fiber#
// (1) Open-Source Boost.Fiber style
#include <boost/fiber/all.hpp>
void HandleRequestBoost() {
int sub_result = 0;
boost::fibers::fiber worker([&sub_result]() {
sub_result = FetchFromBackend(); // Underlying OS thread runs other fibers while waiting!
});
DoOtherLocalWork();
worker.join(); // Suspends only the current fiber until worker finishes
}// (2) Gloop thread::Fiber style (github.com/abseil/gloop)
#include "gloop/thread/fiber/fiber.h"
void HandleRequestFiber() {
int sub_result = 0;
thread::Fiber worker([&sub_result]() {
sub_result = FetchFromBackend();
});
DoOtherLocalWork();
worker.Join(); // Waits for child fiber completion
}Pattern B: Structured Concurrency: Parallel Task Bundles (Bundle / WaitGroup Pattern)#
In backend services, a common pattern is fan-out / fan-in: splitting an incoming request across $N$ backend shards in parallel and waiting for all responses before returning.
Instead of manually managing a std::vector of fiber objects, use a scoped task group (thread::Bundle, analogous to Go’s sync.WaitGroup) whose destructor guarantees that all child fibers have joined before exiting the block:
#include <vector>
#include "gloop/thread/fiber/bundle.h"
std::vector<ShardResponse> QueryAllShardsParallel(const std::vector<int>& shard_ids) {
// Pre-allocate the output vector so each fiber writes to its own distinct slot results[i].
// Because the vector does not resize and indices are disjoint, concurrent writes to
// distinct elements require no extra Mutex!
std::vector<ShardResponse> results(shard_ids.size());
{
thread::Bundle bundle; // Analogous to Go's var wg sync.WaitGroup
for (size_t i = 0; i < shard_ids.size(); ++i) {
// Capture loop index 'i' by value, and containers by reference (&)
bundle.Add([i, &shard_ids, &results]() {
results[i] = QuerySingleShard(shard_ids[i]);
});
}
} // <- ~Bundle() (or bundle.JoinAll()) blocks until all child fibers have finished!
// At this point, all child fibers are guaranteed to have completed.
return results;
}Why Capturing Local Variable
&resultsby Reference Is Safe Here: Becausebundleis declared inside an inner scope (afterresults), its destructor runs beforeresultsgoes out of scope and blocks until every child fiber completes. The parent stack frame (resultsandshard_ids) is guaranteed to outlive all child fibers (Structured Lifetime Guarantee).
3. thread::Channel<T> & thread::Select(): CSP Message Passing in C++ and How It Inspired Go#
Beyond locking shared memory with a Mutex, the second major concurrency paradigm for coordinating fibers is message passing built on C.A.R. Hoare’s CSP (Communicating Sequential Processes) model via thread::Channel<T> and thread::Select() (available in open-source abseil/gloop under gloop/thread/fiber/channel.h and select.h, as well as Boost’s boost::fibers::buffered_channel<T>).
1. How thread::Channel<T> Works#
thread::Channel<T> is a unidirectional, type-safe FIFO producer-consumer stream combining communication and synchronization.
- Unbuffered vs. Buffered Capacity (
buffer_capacity):Channel<T>(0)(Unbuffered / Synchronous): Has no internal buffer; callingWrite()suspends the producer fiber until a matching consumer fiber callsRead()(a direct handshake).Channel<T>(N)(Buffered): Queues up to $N$ items before blocking the writer.
- Separated Endpoints (
Reader<T>vs.Writer<T>):- The creating scope owns the
thread::Channel<T>instance and passesthread::Writer<T>&(or the RAII wrapperthread::WriterCloser<T>) to data sources andthread::Reader<T>&to data sinks, enforcing directionality in the type system.
- The creating scope owns the
#include "gloop/thread/fiber/channel.h"
#include "gloop/thread/fiber/fiber.h"
// 1. Producer: writes items to Writer<T> and closes the channel upon completion.
void ProduceLogs(thread::Writer<LogEntry>* writer) {
// RAII wrapper: automatically calls writer->Close() when leaving scope!
thread::WriterCloser<LogEntry> closer(writer);
for (int i = 0; i < 100; ++i) {
// Check for fiber cancellation to avoid deadlocking if the reader exited early
if (!closer->WriteUnlessCancelled(LogEntry{.id = i})) {
return;
}
}
} // <- ~WriterCloser() automatically calls writer->Close()!
// 2. Consumer: spawns the producer fiber and drains items from Reader<T>.
void ProcessLogs() {
thread::Channel<LogEntry> channel(/*buffer_capacity=*/16);
// Spawn producer fiber with the writer endpoint
thread::Fiber producer([w = channel.writer()]() {
ProduceLogs(w);
});
// Read(&entry) returns true until the writer closes the channel and all buffered items are drained
for (LogEntry entry; channel.reader()->Read(&entry);) {
HandleEntry(entry);
}
producer.Join(); // Join child fiber
}2. thread::Select(): Multiplexing Multiple Channels#
When a fiber needs to wait on multiple channels simultaneously (or wait on a channel alongside cancellation via OnCancel()), it uses thread::Select():
#include "gloop/thread/fiber/channel.h"
#include "gloop/thread/fiber/select.h"
void MergeStreams(thread::Reader<int>* r1, thread::Reader<int>* r2,
thread::Writer<int>* out) {
thread::WriterCloser<int> closer(out);
int val = 0;
bool ok = false;
while (true) {
// Waits until one of the cases is ready, executes it, and returns its 0-based index
int selected = thread::Select({
r1->OnRead(&val, &ok),
r2->OnRead(&val, &ok),
});
if (ok) {
closer->Write(val);
} else {
// One channel closed (ok == false); drain the remaining open channel
thread::Reader<int>* remaining = (selected == 0) ? r2 : r1;
while (remaining->Read(&val)) {
closer->Write(val);
}
break;
}
}
}3. Historical Connection: How C++ thread::Fiber & Channel Directly Inspired Go#
If the C++ code above looks remarkably similar to Go’s concurrency primitives (goroutine, chan, select), that is no coincidence, Go’s concurrency design grew directly out of this exact C++ library experience (see also Go Concurrency: CSP and Channels).
- Historical Context (2005–2007):
- Before co-creating Go in late 2007, Rob Pike (who had earlier designed CSP-based languages Newsqueak, Alef, and Limbo) and colleagues built and used user-space fibers (
thread::Fiber) and CSP channels (thread::Channel,thread::Select) in Google’s C++ server codebase. - When Rob Pike, Ken Thompson, and Robert Griesemer designed Go, they elevated these exact primitives from a C++ library into first-class language syntax:
- Before co-creating Go in late 2007, Rob Pike (who had earlier designed CSP-based languages Newsqueak, Alef, and Limbo) and colleagues built and used user-space fibers (
| CSP Concept | C++ thread:: Library (abseil/gloop) | Go Built-in Language Syntax (2009–) |
|---|---|---|
| Spawn Lightweight Thread | thread::Fiber f([&] { Work(); }); | go Work() |
| Scoped Task Group | thread::Bundle b; b.Add(...); | var wg sync.WaitGroup / errgroup.Group |
| Unbuffered / Buffered Channel | thread::Channel<T> ch(0); / ch(16); | ch := make(chan T) / make(chan T, 16) |
| Directional Channel Endpoints | thread::Reader<T>* / thread::Writer<T>* | <-chan T (receive-only) / chan<- T (send-only) |
| Send / Receive | w->Write(v); / r->Read(&v); | ch <- v / v, ok := <-ch |
| Drain Loop Until Closed | for (T v; r->Read(&v);) { ... } | for v := range ch { ... } |
| Close Channel (RAII) | thread::WriterCloser<T> closer(w); | defer close(ch) |
| Multi-Channel Multiplexing | thread::Select({r1->OnRead(&v, &ok), ...}) | select { case v, ok := <-r1: ... } |
- Why Was a C++ Library Not Enough: Why Create Go?
- Memory Lifetime & Dangling Pointer Hazards (No GC): In C++, if a spawned fiber or a
Select({w->OnWrite(temp)})case outlives a stack-allocated variable by mistake, it causes immediate Use-After-Free (Undefined Behavior). Go combines compiler escape analysis with garbage collection so values shared across goroutines and channels remain valid automatically. - Fixed vs. Dynamically Resizable Stacks: In C++, because arbitrary raw pointers (
int*) can point into a fiber’s stack frame, moving/reallocating a fiber stack at runtime would invalidate pointers. Go’s compiler and runtime track all stack pointers, allowing each goroutine to start with a tiny2 KBstack and dynamically grow or shrink on demand. - First-Class Ergonomics: What required
OnRead(&val, &ok)case arrays and index switching in C++ became a clean, compiler-checkedselect { case ... }statement in Go.
- Memory Lifetime & Dangling Pointer Hazards (No GC): In C++, if a spawned fiber or a
4. Synchronizing Shared State with Open-Source Abseil absl::Mutex#
Whenever multiple threads or fibers access the same memory location and at least one performs a write, you must synchronize access with a mutex to prevent a Data Race (Undefined Behavior in C++).
While C++11 provides std::mutex, large-scale C++ projects overwhelmingly prefer open-source Abseil’s absl::Mutex (#include "absl/synchronization/mutex.h").
1. Why Prefer absl::Mutex Over std::mutex?#
| Feature | C++ Standard (std::mutex + std::condition_variable) | Open-Source Abseil (absl::Mutex) |
|---|---|---|
| RAII Lock Guard | std::lock_guard<std::mutex> / std::unique_lock | absl::MutexLock lock(&mu_); (concise, unified RAII guard) |
| Reader-Writer Locks | Requires changing the mutex type to C++17 std::shared_mutex | Built into every absl::Mutex via absl::ReaderMutexLock & absl::WriterMutexLock |
| Conditional Waiting | Requires a separate std::condition_variable, a manual while (!ready) cv.wait(lck); loop, and manual notify_one() / notify_all() calls | mu_.LockWhen(absl::Condition(...)) built in! Automatically re-evaluates conditions on unlock, no manual notify calls required |
| Deadlock Detection | None (process hangs silently on deadlock) | Tracks lock acquisition order graphs in debug mode and prints stack traces on cycle detection |
| Fiber Awareness | Contention can block the underlying OS kernel thread | Cooperates with user-space fiber schedulers to yield only the waiting fiber |
2. Reader-Writer Locks Compared: Go sync.RWMutex vs. C++17 std::shared_mutex vs. absl::Mutex#
Just as Go provides sync.RWMutex alongside sync.Mutex, standard C++17 provides std::shared_mutex in <shared_mutex>. In Abseil, however, you do not need a separate mutex type at all, every absl::Mutex has Reader-Writer lock (RWMutex) support built directly in:
| Operation | Go (sync.RWMutex) | Standard C++17 (std::shared_mutex) | Open-Source Abseil (absl::Mutex) |
|---|---|---|---|
| Mutex Declaration | var mu sync.RWMutex(separate type from sync.Mutex) | std::shared_mutex mu_;(separate type from std::mutex) | absl::Mutex mu_;(built into the single Mutex type!) |
| Write Lock (Exclusive) | mu.Lock() / defer mu.Unlock() | std::unique_lock lock(mu_);(or std::lock_guard) | absl::MutexLock lock(&mu_);(or absl::WriterMutexLock) |
| Read Lock (Shared) | mu.RLock() / defer mu.RUnlock() | std::shared_lock lock(mu_); | absl::ReaderMutexLock lock(&mu_); |
// [1] Standard C++17: std::shared_mutex + std::shared_lock / std::unique_lock
#include <mutex>
#include <shared_mutex>
#include <unordered_map>
class StdCache {
public:
int Get(int key) const {
std::shared_lock<std::shared_mutex> read_lock(mu_); // Like Go's mu.RLock() (concurrent readers allowed)
auto it = data_.find(key);
return (it != data_.end()) ? it->second : -1;
}
void Put(int key, int value) {
std::unique_lock<std::shared_mutex> write_lock(mu_); // Like Go's mu.Lock() (exclusive writer)
data_[key] = value;
}
private:
mutable std::shared_mutex mu_;
std::unordered_map<int, int> data_;
};// [2] Abseil: single absl::Mutex type with ReaderMutexLock / MutexLock (WriterMutexLock)
#include "absl/synchronization/mutex.h"
class AbseilCache {
public:
int Get(int key) const {
absl::ReaderMutexLock read_lock(&mu_); // Like Go's mu.RLock() (shared reader lock)
return LookupInternal(key);
}
void Put(int key, int value) {
absl::MutexLock write_lock(&mu_); // Like Go's mu.Lock() (exclusive writer lock)
InsertInternal(key, value);
}
private:
mutable absl::Mutex mu_; // RWMutex capability is built into every absl::Mutex!
};3. Declarative Conditional Waiting with absl::Mutex::LockWhen#
With absl::Mutex and absl::Condition, implementing a thread-safe bounded queue requires zero std::condition_variable boilerplate or notify calls:
#include <deque>
#include "absl/synchronization/mutex.h"
template <typename T>
class ThreadSafeQueue {
public:
void Push(T item) {
absl::MutexLock lock(&mu_);
queue_.push_back(std::move(item));
// No cv.notify_one() needed!
// When ~MutexLock unlocks mu_, Abseil automatically checks waiters' conditions.
}
T Pop() {
// Waits until queue_ is non-empty, then acquires the exclusive lock!
auto not_empty = +[](std::deque<T>* q) { return !q->empty(); };
mu_.LockWhen(absl::Condition(not_empty, &queue_));
T item = std::move(queue_.front());
queue_.pop_front();
mu_.Unlock();
return item;
}
private:
absl::Mutex mu_;
std::deque<T> queue_;
};5. Compile-Time Thread Safety Analysis (ABSL_GUARDED_BY)#
Concurrency bugs are notoriously difficult to debug because forgetting to lock a mutex before accessing shared state compiles cleanly and only fails intermittently under production load.
Open-source Abseil’s #include "absl/base/thread_annotations.h" integrates with Clang’s static analyzer (-Wthread-safety) to turn missing locks and lock-order violations into compile-time errors with zero runtime overhead.
Four Essential Thread Safety Annotations#
Annotation (absl/base/thread_annotations.h) | Target | Rule Enforced by the Compiler |
|---|---|---|
ABSL_GUARDED_BY(mu_) | Member variable | Reading or writing this variable requires holding mu_. |
ABSL_PT_GUARDED_BY(mu_) | Pointer / smart pointer member | Dereferencing the pointed-to data (*ptr_) requires holding mu_. |
ABSL_LOCKS_EXCLUDED(mu_) | public member function | Caller must not already hold mu_ when calling this function (prevents self-deadlock). |
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) | private mutating helper | Caller must already hold an exclusive (write) lock (MutexLock / WriterMutexLock) on mu_ (holding only ReaderMutexLock triggers a compile error!). |
ABSL_SHARED_LOCKS_REQUIRED(mu_) | private read-only helper | Caller must hold at least a shared (reader) lock (ReaderMutexLock) on mu_. |
Complete Example with ABSL_GUARDED_BY#
#include <string>
#include "absl/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/synchronization/mutex.h"
class AccountBalanceManager {
public:
// Public methods acquire mu_ internally, so the caller must not already hold mu_.
void Deposit(int account_id, int amount) ABSL_LOCKS_EXCLUDED(mu_) {
absl::MutexLock lock(&mu_); // Acquire RAII lock
balances_[account_id] += amount;
UpdateAuditLogLocked(account_id, amount); // ✅ Allowed because mu_ is held!
}
int GetBalance(int account_id) const ABSL_LOCKS_EXCLUDED(mu_) {
// ❌ Commenting out the ReaderMutexLock line below triggers an immediate compile error:
// error: reading variable 'balances_' requires holding mutex 'mu_' [-Wthread-safety-analysis]
absl::ReaderMutexLock read_lock(&mu_);
auto it = balances_.find(account_id);
return (it != balances_.end()) ? it->second : 0;
}
private:
// Naming private helpers with a 'Locked' suffix and ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_)
// ensures they can only be called while mu_ is already held (preventing double-lock deadlocks).
void UpdateAuditLogLocked(int account_id, int delta)
ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
total_transactions_++;
}
// Declared mutable so const methods (like GetBalance) can acquire reader locks.
mutable absl::Mutex mu_;
// Registered with the compiler: cannot be read or written without holding mu_!
absl::flat_hash_map<int, int> balances_ ABSL_GUARDED_BY(mu_);
int total_transactions_ ABSL_GUARDED_BY(mu_) = 0;
};Best Practice: Separating
publicMethods fromprivate ...Locked()Helpers: Because bothstd::mutexandabsl::Mutexare non-recursive, if onepublicmethod locksmu_and calls anotherpublicmethod that also tries to lockmu_, the thread will immediately self-deadlock. Always annotatepublicentry points withABSL_LOCKS_EXCLUDED(mu_)and delegate shared internal work toprivatehelpers suffixed withLockedand annotated withABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_).
6. Thread-Safe vs. Thread-Compatible Design Contracts#
Both the C++ standard library and open-source Abseil classify types into two distinct concurrency contracts:
| Classification | Definition | Examples | Concurrent Reads (const) | Concurrent Writes (Non-const) |
|---|---|---|---|---|
Thread-Compatible | No internal synchronization. Safe for concurrent reads, but any write requires external locking (Mutex) by the caller | std::vector, std::string, absl::flat_hash_map, most value types | ✅ Safe without external locks | ❌ Requires external Mutex |
Thread-Safe | Internally synchronized (via internal Mutex or std::atomic). Safe for concurrent operations from multiple threads without external locks | absl::Mutex, AccountBalanceManager above, concurrent queues/caches | ✅ Safe | ✅ Safe without external locks |
Why Most C++ Containers (std::vector, etc.) Are Thread-Compatible Rather Than Thread-Safe#
- Zero-Overhead Principle for Single-Threaded Code: If
std::vector::push_back()acquired an internal mutex on every call, single-threaded programs and callers that already hold a higher-level lock would pay unnecessary atomic synchronization overhead on every operation. - Method-Level Locking Cannot Guarantee Transaction-Level Atomicity:
- Even if
vector::empty()andvector::pop_back()each locked an internal mutex individually, a compound check-then-act sequence would still suffer from a classic TOCTOU (Time-of-Check to Time-of-Use) race condition:if (!vec.empty()) { // (1) Vector has 1 element at check time, // <-- Another thread intervenes here and pops the last element! vec.pop_back(); // (2) Pops from an empty vector -> Undefined Behavior! } - Meaningful synchronization must happen at the granularity of the owning domain object (
AccountBalanceManager) usingABSL_GUARDED_BY(mu_).
- Even if