C++11 introduced a standardized thread library covering core capabilities such as thread creation, synchronization primitives, and asynchronous tasks. Since then, C++17/20 has continued to strengthen it (parallel algorithms, std::jthread, std::latch/std::barrier), moving multithreaded programming from platform-specific pthread/Win32 toward a portable standard paradigm.
Thread Creation and Management
std::thread
| |
Key rule: before a std::thread object is destroyed, you must call join() or detach(); otherwise the program terminates immediately.
std::jthread (C++20)
jthread improves on it in two ways: it automatically calls join() on destruction (no manual call needed), and it supports cooperative interruption (stop_token):
| |
Synchronization Mechanisms
std::mutex — Mutual Exclusion Lock
The most basic exclusive lock; only one thread can enter the critical section at a time. C++ provides three RAII lock wrappers with different usage patterns:
lock_guard — The Simplest RAII
Locks on construction and unlocks on destruction. Cannot be manually unlocked, copied, or moved. Suitable for scenarios where the critical section has clear boundaries and does not need to be unlocked midway:
| |
unique_lock — Flexible but Somewhat Heavier
Compared with lock_guard, it wraps an extra bool (tracking whether the lock is held), trading that for more capabilities:
| |
Comparison of the Three
lock_guard | unique_lock | scoped_lock (C++17) | |
|---|---|---|---|
| Manual unlock | ❌ | ✅ | ❌ |
| Deferred locking | ❌ | ✅ | ❌ |
| Movable | ❌ | ✅ | ❌ |
| Lock multiple mutexes at once without deadlock | ❌ | ❌ (must manually use std::lock) | ✅ built-in capability |
| Works with condition_variable | ❌ | ✅ | ❌ |
| Size | Lightest (1B) | Slightly larger (usually 8-16B) | Similar to lock_guard |
| When to use | Simple critical section (90% of cases) | Need flexible lock control, work with cv | Need to lock two or more mutexes at once |
Rule of thumb: If lock_guard works, don’t use unique_lock; the code is simpler and the intent is clearer.
Why can unique_lock manually unlock while lock_guard cannot?
This is a deliberate design choice, not a technical impossibility. Both are essentially RAII wrappers around a mutex; the difference is whether to expose flexible control:
| |
lock_guard could absolutely have an unlock() method added, but the committee deliberately did not add one—one of C++’s core philosophies is “express intent with types.” The name lock_guard says “I am an RAII guard; the lock’s holding period = my lifetime,” with no possibility of midway release. If you see unique_lock, you know there may be more complex lock operations here.
Can scoped_lock completely replace lock_guard?
Technically yes, but not recommended in terms of code intent. For the single-mutex case:
| |
The difference lies in the hint given when reading the code. scoped_lock is designed for “multiple locks to prevent deadlock”; seeing it, readers subconsciously look for whether other mutexes are involved. Using lock_guard clearly conveys “this is a simple single-lock critical section.” So in practice:
- Single mutex →
lock_guard(clearest intent) - Multiple mutexes →
scoped_lock(needs deadlock prevention) - Need flexible control / work with cv →
unique_lock
The core advantage of std::scoped_lock is that locking multiple mutexes at once does not deadlock (it internally uses the std::lock algorithm):
| |
std::shared_mutex — Reader-Writer Lock (C++17)
Allows multiple readers to access concurrently while a writer has exclusive access. Suitable for read-heavy, write-light scenarios:
| |
std::condition_variable — Condition Variable
A condition variable solves a core problem: letting a thread suspend and wait when a condition is not satisfied, instead of busy-waiting and wasting CPU. Used together with a mutex, it is the standard tool for the producer-consumer pattern.
How wait() Works
cv.wait(lock, predicate) internally performs three steps, completing lock release and waiting atomically throughout:
| |
This is why condition_variable must work with unique_lock rather than lock_guard—wait() needs to repeatedly unlock/lock internally, and lock_guard does not support manual unlocking.
Practical Example: Network Thread → Logic Thread Task Dispatch
The most common pattern in game servers: an IO thread receives network packets, and a logic thread processes messages. The logic thread suspends when idle without consuming CPU, wakes up immediately when a message arrives, and periodically performs heartbeat checks.
| |
This pattern appears over and over in game servers everywhere—the IO thread only receives/sends packets and posts them, the logic thread runs the main loop single-threaded, and condition_variable handles suspending when idle, waking when messages arrive, and doing background maintenance on timeout.
After entering wait, will the thread never wake up without notify?
It depends on which kind of wait() you use:
| |
A wait() with a predicate internally does three things:
- First check the predicate—if it is already
true, it will not sleep at all and returns directly - Only when the predicate is
falsedoes it release the lock and suspend - After being woken up (whether by
notifyor a spurious wakeup), it rechecks the predicate: iffalse, it goes back to sleep; only iftruedoes it return
So the accurate statement is: after entering wait, the thread sleeps until woken up, but after waking, if the condition is not satisfied, it puts itself back to sleep. Without notify (and without a wait_for timeout), it theoretically blocks forever; although the OS may spuriously wake it, the predicate is not satisfied so it goes back to sleep, and externally it still appears “stuck.”
This is also why modifying the condition must be done inside the lock—if the producer inserts a condition modification + notify between the consumer’s predicate check and suspension, that notify is lost:
| |
Fortunately, cv.wait()’s “release lock + enter wait queue” is completed atomically at the kernel level—between the consumer finishing the predicate check and actually suspending, even if the producer acquires the lock it cannot insert a notify (because the consumer enters the wait queue at the same time it releases the lock, so the producer’s notify can hit it). This is the fundamental reason condition_variable must be bound to a mutex.
notify_one vs notify_all
Let’s understand it first with a concrete scenario:
| |
notify_one() | notify_all() | |
|---|---|---|
| Behavior | Wakes one (not guaranteed which) | Wakes all |
| Cost | Low | High (all wake up and contend for the lock, only one gets it, the rest go back to sleep—thundering herd) |
| Used for | Each task pushed into a task queue | Shutdown notifications, state resets, and other changes that “everyone needs to respond to” |
Simple rule: exactly one thread can consume this event → notify_one; every thread needs to react to this event → notify_all.
Spurious Wakeup
A condition variable may wake up on its own without any notify, which is an operating-system-level characteristic (explicitly allowed by the POSIX standard). So never write this:
| |
Lost Wakeup
If notify happens before wait, and the waiting thread has not yet entered the waiting state—that notify is lost. This is exactly why you must hold the mutex before modifying the condition:
| |
If notify is placed inside the lock, after being woken up the consumer must wait for the lock to be released before continuing—adding an unnecessary context switch. So placing notify after unlocking is the recommended practice (of course, putting it inside the lock is also semantically correct, just slightly worse for performance).
Waiting with Timeout
| |
In game servers, wait_for is often used for heartbeat detection—adding a timeout while waiting on a task queue to periodically check whether connections have been dropped.
Summary of Common Pitfalls
| Pitfall | Consequence | Correct Approach |
|---|---|---|
Using if instead of while / no predicate | Spurious wakeup causes inconsistent state | Always use a predicate |
| notify before modifying the condition | Lost wakeup (consumer may wait forever) | Modify the condition first, then notify |
| Mixing different conditions on the same cv | A thread is woken by an event it should not care about | Use different cvs for different conditions |
| Threads still waiting during destruction | Undefined behavior | notify_all + join threads before destroying the cv |
| Exception thrown inside wait | Mutex state is uncertain | Do not throw exceptions in the predicate |
std::atomic and Memory Order
std::atomic provides indivisible atomic operations and is the cornerstone of lock-free programming:
| |
The key point is Memory Order—it controls the visibility ordering of ordinary memory accesses around atomic operations:
| Memory Order | Meaning | Cost |
|---|---|---|
relaxed | Guarantees atomicity only, not ordering | Lightest, equivalent to ordinary atomic instructions |
acquire | Subsequent reads/writes cannot be reordered before it | Read-side barrier |
release | Preceding reads/writes cannot be reordered after it | Write-side barrier |
acq_rel | Combines acquire + release | For RMW operations |
seq_cst | Global sequential consistency (default) | Heaviest, usually has a full memory barrier |
Lock-free programming has a narrow range of scenarios in game servers—in the vast majority of cases, locks are enough. Only when the critical section is extremely small (a few lines of code), contention is frequent, and lock holding time is extremely short do lock-free structures have an advantage. Typical scenarios: Reference Counting, statistical counters, and SPSC (single-producer single-consumer) queues.
std::call_once and std::once_flag
Guarantees that some initialization logic runs only once; it is thread-safe and more concise and efficient than using mutex + bool flag:
| |
Commonly used for lazy-loaded singletons and global configuration initialization. It is usually implemented with atomic underneath and is much faster than manual locking.
std::latch and std::barrier (C++20)
Both are thread synchronization barriers—they make multiple threads wait for each other at a point, then proceed together once all have arrived. Their essential difference is how many times they can be used:
| |
std::latch — One-Shot Countdown Latch
It is like a counter that can only go down, never up. Initialize it with a number N; when a thread arrives, arrive_and_wait() or count_down() decrements the count by 1. When it reaches 0, the latch opens and all waiting threads are released. Once it reaches 0, it never closes again.
Practical scenario: wait for all threads to finish initialization before starting service
| |
Output (regardless of thread ordering, the last line always comes after all “init done” lines):
| |
Lighter usage: one-shot wait
| |
This is much more concise than the combination of condition_variable + bool flag + mutex, and it has no wakeup/lost-wakeup issues.
std::barrier — Reusable Phase Synchronization
After all threads arrive in each phase: the barrier automatically resets the count to its initial value, triggers a completion callback, and then everyone proceeds to the next phase.
Practical scenario: phased parallel processing — game server frame loop
The classic usage is to split the world into N parts each frame for worker threads to update in parallel, with the main thread performing aggregation serially after each phase, then moving to the next phase:
| |
The timeline will be:
| |
No manual counting, no manual notification, no need to worry about spurious wakeups—barrier handles it all.
latch vs barrier vs condition_variable
latch | barrier | condition_variable | |
|---|---|---|---|
| Core semantics | Countdown; opens permanently at 0 | Phase synchronization; auto-reset | Condition wait + notification |
| Reusable | ❌ One-shot | ✅ Unlimited | ✅ |
| Wait for N threads to arrive | ✅ Native support | ✅ Native support | ❌ Requires manual counting |
| Phase completion callback | ❌ | ✅ | ❌ |
| When to use | Initialization’s “wait for everyone to be ready before proceeding” | Parallel computing’s “arrive at each phase → aggregate → next phase” | Arbitrary condition waiting (wait for data, wait for timeout, wait for state change) |
thread_local
A variable copy exclusive to each thread. With the same variable name, different threads access completely different memory locations—naturally thread-safe, with no lock required.
| |
Underlying Mechanism
The key lies in cooperation between the operating system and the compiler. The OS allocates a private TLS (Thread Local Storage) area for each thread, and the compiler’s addressing of thread_local variables is automatically redirected to that area:
| |
The specific process:
- Compile Time—the compiler recognizes the
thread_localvariable and places it in a special.tdata/.tbsssection rather than an ordinary data section. It also computes the variable’s offset within the thread’s TLS. - Runtime—when each thread is created, the OS allocates an independent TLS storage block for it and stores the block’s base address in a specific hardware register (Windows uses the
gssegment register, Linux uses thefssegment register). The main thread also has its own TLS block. - On access—the code generated by the compiler is not an ordinary
[全局地址]access, but indirect addressing via[TLS基址寄存器 + offset]. Because each thread’s base register contents differ, the sameoffsetlands in different physical memory.
In pseudo-assembly, it looks like this:
| |
For dynamically loaded thread_local (such as a .so loaded by dlopen), because the offset cannot be determined at Compile Time, it goes through the slower __tls_get_addr() call path, which is an order of magnitude slower than segment-register offset addressing. However, thread_local variables in the main program do not have this problem.
Typical Uses
- Thread-private random number generator—each thread has an independent seed, with no interference
- Log buffer—each thread accumulates a batch and then flushes, avoiding contention on the global log lock
- errno—the C standard library’s
errnois implemented with TLS, soerrnois also safe in multithreaded programs
Notes
- Abusing
thread_localcauses total memory bloat—1000 threads × 4KB of private data per thread = 4MB extra thread_localobjects with non-trivial destructors may have destruction-order issues at thread exit in C++11~17 (improved in C++20)- Suitable for thread-private caches, random number generators, and log buffers. But note: abusing thread_local causes memory bloat.
Asynchronous Tasks: std::future / std::promise / std::async
| |
Note: if std::async is not given the launch::async argument, the standard library may choose synchronous execution (deferred evaluation); this is a common pitfall.
Thread Pool
The core idea of a Thread Pool is simple: pre-create N resident threads that share a task queue; when there is work, they do it, and when there is none, they suspend. The overhead of thread creation and destruction is amortized over the lifetimes of the N threads.
Why Use a Thread Pool
Each time std::thread t(fn) creates a thread, the OS must allocate stack space, initialize TLS, and set up kernel scheduling structures—this overhead is roughly tens to hundreds of microseconds. A lightweight task itself may take only a few microseconds. In such scenarios, more time is spent “creating threads” than “doing real work,” causing overall task throughput to be lower than single-threaded serial execution (because thread management overhead completely cancels out the benefit of parallel processing).
A Thread Pool solves this class of problems by reusing threads, keeping the same batch of threads running continuously, thereby keeping the overhead of task distribution, enqueueing, and lock contention at a low level.
Differences among Threads, Thread Pools, and Coroutines:
Thread Thread Pool Coroutine Scheduler OS kernel preemption Task queue + cv User code actively yield/await Context-switch cost ~µs level (kernel mode) ~µs level (still threads) ~ns level (pure user mode) Stack Allocated independently per thread (~1MB) Same as above Shared coroutine frame (~a few KB) Suitable for Arbitrary time-consuming tasks Avoiding frequent thread creation/destruction Massive concurrent IO waits Thread Pools solve the problem of “using threads to do work is too expensive”; Coroutines solve the problem of “waiting for IO wastes threads”. One pools execution resources, the other prevents execution resources from being blocked. In practice, the two are often combined—the Thread Pool serves as the underlying executor for Coroutines, and Coroutines are scheduled on the threads in the pool.
A Simple Thread Pool Implementation
| |
Although this implementation is only about 50 lines, it contains the core mechanisms of a Thread Pool:
- Pre-created threads: the constructor creates the specified number of threads according to the parameter, and these threads keep running for the object’s lifetime
- Shared task queue: all threads compete to take tasks from the same
tasks_queue - Suspend when idle: when the queue is empty,
cv_.wait()puts threads into a waiting state without consuming CPU time - Graceful shutdown: during destruction, first set the
stop_flag, thennotify_all()to wake all threads. Each thread checksstop_ && tasks_.empty()after waking; if the condition is met, it exits the loop and joins. This ensures all already-enqueued tasks finish before it truly stops. - Release the lock between task executions: the
task()call is outside theunique_lockscope—this ensures no lock is held while executing a task, so it does not block other threads from taking the next task from the queue
Usage Example
| |
Practical Applications in Game Servers
The most common use of Thread Pools in game servers is to throw time-consuming operations that do not depend on ordering into the pool, keeping the main logic thread lightweight:
| Scenario | Approach |
|---|---|
| Database writes | Player save persistence → throw into the Thread Pool for asynchronous writes; the main thread does not block |
| Log persistence | Log buffer accumulates a batch → submit to the Thread Pool for flush |
| Matchmaking computation | Receive a matchmaking request → the Thread Pool computes scores asynchronously and writes them into the match result queue |
| Pathfinding | Split large-scale Pathfinding into independent tasks → parallel computation in the Thread Pool |
Key principle: do not let the main logic thread perform any operation that may block for a long time. The main logic thread is only responsible for receiving/sending network packets, updating the State Machine, and posting time-consuming tasks to the Thread Pool, then immediately returning to the loop to process the next message.
Comparison of Lock Use Cases
| Lock Type | Applicable Scenario | Characteristics |
|---|---|---|
std::mutex | Critical sections with clear read/write operations and medium lock holding time | General-purpose, involves kernel-mode switching |
std::shared_mutex | Reads far outnumber writes | Concurrent reads, exclusive writes, heavier than mutex |
Spinlock (atomic_flag) | Extremely short critical sections (a few lines of code) | User-mode busy-wait, no kernel switch, wastes CPU |
condition_variable | Need to wait for a condition to be satisfied | Works with mutex, supports notify |
std::atomic + CAS | Single-variable Atomic Operations, lock-free queues | Extremely lightweight, difficult to implement correctly |
Example spinlock implementation (the C++ standard library does not directly provide std::spinlock):
| |
A spinlock is effective when the critical section is very short (cheaper than a thread switch), but if the critical section contains system calls or lock contention is intense, it is actually worse than mutex. In game servers, spinlocks are suitable for protecting a single variable or extremely short queue operations.
Q&A
In multithreaded programming, what synchronization mechanisms does C++ provide? Please compare the applicable scenarios of mutexes, reader-writer locks, and spinlocks. What is the principle of CAS in lock-free programming? Which scenarios in game servers are suitable for lock-free structures?
C++ synchronization mechanisms: The standard library provides std::mutex (mutex), std::shared_mutex (reader-writer lock), std::condition_variable (condition variable), std::atomic (Atomic Operation), std::call_once, std::latch/std::barrier (C++20), etc. A spinlock can be implemented using TAS (test-and-set) on std::atomic_flag.
Comparison of applicable scenarios:
- Mutex: The most general-purpose; use it when the critical section is medium to long. Under contention, threads enter kernel-mode sleep and do not waste CPU.
- Reader-writer lock (shared_mutex): Use it when reads are many and writes are few—multiple readers can run concurrently, while a writer has exclusive access. But the lock itself is heavier than a mutex; if the critical section is very short or reads are not frequent either, it is better to use a mutex directly.
- Spinlock: Use it when the critical section is extremely short (a few instructions); it busy-waits in user mode and avoids the kernel overhead of thread switching. But if system calls or IO appear in the critical section, it is actually worse.
Principle of CAS in lock-free programming: CAS (Compare-And-Swap) is an atomic instruction provided by the CPU. The logic is: compare whether the value at the target address equals the expected value; if equal, replace it with the new value, otherwise do nothing; the whole process is atomic. All operations either fully succeed or fully fail. C++ exposes it through atomic<T>::compare_exchange_weak/strong. CAS can be used to build lock-free stacks and lock-free queues—turn pointer modifications into a CAS loop, retry on failure, and avoid lock overhead. The cost is that code correctness is extremely difficult to verify (ABA problem, memory reclamation problem).
Applicable lock-free scenarios in game servers: Lock-free is suitable for places where the critical section is extremely short and contention is frequent—such as log queues (SPSC lock-free queue, with the log thread and business thread on each end), global counters (online player count statistics, directly using atomic’s fetch_add with zero contention), and fast allocation from an Object Pool (CAS to grab a slot). Most business logic is simpler and more reliable with a mutex directly; do not go lock-free just for the sake of being “lock-free.”