Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # C++ Concurrency: `std::thread` vs. Lightweight Fibers, `Channel`, & Abseil `Mutex` {{< katex />}} 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` & `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)**. ```text [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:** 1. **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. 2. **Expensive Creation & Destruction:** Creating or destroying an OS thread requires kernel system calls (`clone()`). 3. **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`](https://www.boost.org/doc/libs/release/libs/fiber/), Meta's [`folly::fibers`](https://github.com/facebook/folly/tree/main/folly/fibers), or open-source Abseil [Gloop's `thread::Fiber`](https://github.com/abseil/gloop): 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 pointer `RIP`, 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` 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_await` coroutines are *stackless*, a coroutine can only suspend its direct frame; in a call chain `A() -> B() -> C()`, if `C()` needs to suspend, `A`, `B`, and `C` must all be rewritten to return coroutine types and use `co_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]({{< relref "/programming/cpp/raii.md" >}}) by **automatically requesting stop and calling `join()` in its destructor**, eliminating accidental `std::terminate()` crashes. ```cpp #include #include #include #include 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(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:** > Calling `t.detach()` relinquishes control over when the thread finishes. If a detached thread references local stack variables, `this`, or static objects destroyed during `main()` 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 ```cpp // (1) Open-Source Boost.Fiber style #include 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 } ``` ```cpp // (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: ```cpp #include #include "gloop/thread/fiber/bundle.h" std::vector QueryAllShardsParallel(const std::vector& 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 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 `&results` by Reference Is Safe Here:** > Because `bundle` is declared inside an inner scope (after `results`), its destructor runs *before* `results` goes out of scope and **blocks until every child fiber completes**. The parent stack frame (`results` and `shard_ids`) is guaranteed to outlive all child fibers (**Structured Lifetime Guarantee**). --- ## 3. `thread::Channel` & `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`** and **`thread::Select()`** (available in open-source [`abseil/gloop`](https://github.com/abseil/gloop) under `gloop/thread/fiber/channel.h` and `select.h`, as well as Boost's `boost::fibers::buffered_channel`). ### 1. How `thread::Channel` Works `thread::Channel` is a unidirectional, type-safe FIFO producer-consumer stream combining communication and synchronization. - **Unbuffered vs. Buffered Capacity (`buffer_capacity`):** - **`Channel(0)` (Unbuffered / Synchronous):** Has no internal buffer; calling `Write()` suspends the producer fiber until a matching consumer fiber calls `Read()` (a direct handshake). - **`Channel(N)` (Buffered):** Queues up to $N$ items before blocking the writer. - **Separated Endpoints (`Reader` vs. `Writer`):** - The creating scope owns the `thread::Channel` instance and passes **`thread::Writer&`** (or the RAII wrapper **`thread::WriterCloser`**) to data sources and **`thread::Reader&`** to data sinks, enforcing directionality in the type system. ```cpp #include "gloop/thread/fiber/channel.h" #include "gloop/thread/fiber/fiber.h" // 1. Producer: writes items to Writer and closes the channel upon completion. void ProduceLogs(thread::Writer* writer) { // RAII wrapper: automatically calls writer->Close() when leaving scope! thread::WriterCloser 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. void ProcessLogs() { thread::Channel 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()`: ```cpp #include "gloop/thread/fiber/channel.h" #include "gloop/thread/fiber/select.h" void MergeStreams(thread::Reader* r1, thread::Reader* r2, thread::Writer* out) { thread::WriterCloser 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* 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]({{< relref "/programming/go/concurrency/csp.md" >}})). - **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**: | 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 ch(0);` / `ch(16);` | `ch := make(chan T)` / `make(chan T, 16)` | | **Directional Channel Endpoints** | `thread::Reader*` / `thread::Writer*` | `<-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 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?** 1. **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. 2. **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 tiny **`2 KB` stack** and dynamically grow or shrink on demand. 3. **First-Class Ergonomics:** What required `OnRead(&val, &ok)` case arrays and index switching in C++ became a clean, compiler-checked `select { case ... }` statement in Go. --- ## 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`](https://abseil.io/docs/cpp/guides/synchronization)** (`#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::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 ``**. 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_);`** | ```cpp // [1] Standard C++17: std::shared_mutex + std::shared_lock / std::unique_lock #include #include #include class StdCache { public: int Get(int key) const { std::shared_lock 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 write_lock(mu_); // Like Go's mu.Lock() (exclusive writer) data_[key] = value; } private: mutable std::shared_mutex mu_; std::unordered_map data_; }; ``` ```cpp // [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: ```cpp #include #include "absl/synchronization/mutex.h" template 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* 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 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` ```cpp #include #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 balances_ ABSL_GUARDED_BY(mu_); int total_transactions_ ABSL_GUARDED_BY(mu_) = 0; }; ``` > **Best Practice: Separating `public` Methods from `private ...Locked()` Helpers:** > Because both `std::mutex` and `absl::Mutex` are **non-recursive**, if one `public` method locks `mu_` and calls another `public` method that also tries to lock `mu_`, the thread will immediately **self-deadlock**. Always annotate `public` entry points with `ABSL_LOCKS_EXCLUDED(mu_)` and delegate shared internal work to `private` helpers suffixed with `Locked` and annotated with `ABSL_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` 1. **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. 2. **Method-Level Locking Cannot Guarantee Transaction-Level Atomicity:** - Even if `vector::empty()` and `vector::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**: ```cpp 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`) using `ABSL_GUARDED_BY(mu_)`.