Multithreading-Related Mechanisms in C++

Words: 5008

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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#include <thread>
#include <iostream>
using namespace std;

void worker(int id, const string& msg) {
    cout << "thread " << id << ": " << msg << endl;
}

int main() {
    thread t1(worker, 1, "hello");
    thread t2(worker, 2, "world");

    t1.join();  // 等待 t1 结束
    t2.join();  // 等待 t2 结束
    // 不 join 也不 detach 就析构 → std::terminate!
    return 0;
}

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):

cpp
1
2
3
4
5
6
7
8
void worker(stop_token st) {
    while (!st.stop_requested()) {
        // 干活...
    }
}

jthread t(worker);
// 离开作用域时自动请求停止并 join

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:

cpp
1
2
3
4
5
6
7
8
int counter = 0;
mutex mtx;

void increment() {
    lock_guard<mutex> lg(mtx);  // 构造 = lock,离开作用域 = unlock
    ++counter;
    // 到 } 自动析构解锁,异常安全
}

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
mutex mtx;

// 1. 延迟加锁
unique_lock<mutex> ul(mtx, defer_lock);  // 构造时不 lock
ul.lock();    // 稍后手动加锁
ul.unlock();  // 手动解锁
ul.lock();    // 再次加锁

// 2. 尝试加锁(不阻塞)
if (ul.try_lock()) { /* 拿到锁了 */ }

// 3. 转移所有权
auto ul2 = std::move(ul);  // ul 释放锁的所有权给 ul2

// 4. condition_variable 只能用 unique_lock
//    因为 cv.wait() 内部需要反复 unlock/lock,lock_guard 做不到
cv.wait(ul, []{ return ready; });

Comparison of the Three

lock_guardunique_lockscoped_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❌✅❌
SizeLightest (1B)Slightly larger (usually 8-16B)Similar to lock_guard
When to useSimple critical section (90% of cases)Need flexible lock control, work with cvNeed 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
lock_guard:
  ├── 内部只管两件事:构造时 mtx.lock(),析构时 mtx.unlock()
  ├── 没有任何状态标志、没有任何控制接口
  └── 设计意图:看到 lock_guard = 这个锁会被持满整个作用域,一眼明白

unique_lock:
  ├── 内部多了一个 bool owns_,追踪"当前是否持有锁"
  ├── unlock()  →  mtx.unlock(); owns_ = false;
  ├── lock()    →  mtx.lock();   owns_ = true;
  ├── 析构时    →  if (owns_) mtx.unlock();
  └── 设计意图:需要灵活操控锁的场景(cv、延迟加锁、转移所有权)

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:

cpp
1
2
lock_guard<mutex> lg(mtx);    // 一眼看出:单锁,简单保护区
scoped_lock<mutex> sl(mtx);   // 功能完全相同,零额外开销

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):

cpp
1
2
mutex mtx1, mtx2;
scoped_lock sl(mtx1, mtx2);  // 原子地锁定两个,不会死锁

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
shared_mutex rw;
int data = 0;

void reader() {
    shared_lock sl(rw);     // 共享锁,多个 reader 可以同时持有
    // 读取 data...
}

void writer() {
    unique_lock ul(rw);     // 排他锁,只有一个人能持有
    ++data;
}

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:

1
2
3
1. 检查谓词 → true 就直接返回(不等待)
2. 谓词为 false → 原子地:释放 lock + 线程进入等待队列(阻塞)
3. 被唤醒后 → 重新获取 lock,再次检查谓词(应对虚假唤醒)

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.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;

struct NetMessage {
    int conn_id;
    string payload;
};

class LogicThread {
    mutex mtx_;
    condition_variable cv_;
    queue<NetMessage> msg_queue_;
    bool running_ = true;

public:
    // 网络线程调用:投递消息
    void post_message(NetMessage msg) {
        {
            lock_guard lg(mtx_);
            msg_queue_.push(std::move(msg));
        }
        cv_.notify_one();  // 唤醒逻辑线程
    }

    // 主线程调用:通知停机
    void shutdown() {
        {
            lock_guard lg(mtx_);
            running_ = false;
        }
        cv_.notify_all();
    }

    // 逻辑线程主循环
    void run() {
        while (true) {
            unique_lock ul(mtx_);

            // 等 100ms —— 要么有消息,要么超时
            bool has_msg = cv_.wait_for(ul, 100ms, [this] {
                return !msg_queue_.empty() || !running_;
            });

            if (!running_ && msg_queue_.empty()) {
                break;  // 停机且队列处理完毕
            }

            // 处理所有积压消息
            while (!msg_queue_.empty()) {
                NetMessage msg = std::move(msg_queue_.front());
                msg_queue_.pop();
                ul.unlock();       // 处理时不持锁
                process(msg);
                ul.lock();
            }

            if (!has_msg) {
                // 100ms 内没消息,做后台维护
                ul.unlock();
                check_heartbeats();
            }
        }
    }

private:
    void process(const NetMessage& msg) {
        cout << "conn " << msg.conn_id << ": " << msg.payload << endl;
    }

    void check_heartbeats() {
        cout << "[heartbeat check]" << endl;
    }
};

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:

cpp
1
2
3
4
5
// 形式 1:不带谓词 —— 醒来后不会自动重新检查
cv.wait(lock);  // 被 notify 或虚假唤醒后返回,不管条件是否真正满足

// 形式 2:带谓词 —— 等价于 while(!pred) { wait(lock); }
cv.wait(lock, [] { return ready; });

A wait() with a predicate internally does three things:

  1. First check the predicate—if it is already true, it will not sleep at all and returns directly
  2. Only when the predicate is false does it release the lock and suspend
  3. After being woken up (whether by notify or a spurious wakeup), it rechecks the predicate: if false, it goes back to sleep; only if true does 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:

1
2
3
4
5
消费者                              生产者
  持有锁,检查 ready == false
  准备释放锁+挂起(原子操作)
                                    lock, ready = true, notify_one (waiting queue 还是空的!)
  释放锁+挂起 ---> 永远睡下去了!

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
3 个消费者都在 wait,等待队列中处理新消息:
  线程 A: [阻塞]  线程 B: [阻塞]  线程 C: [阻塞]

生产者放入 1 条消息,调用 notify_one():
  线程 A: [醒来处理消息]  线程 B: [阻塞]  线程 C: [阻塞]
  → 只醒了 1 个,因为只有 1 条消息,唤醒更多也是浪费

生产者调用 shutdown,调用 notify_all():
  线程 A: [醒来,看到 done=true,退出]
  线程 B: [醒来,看到 done=true,退出]
  线程 C: [醒来,看到 done=true,退出]
  → 全醒了,因为"停机"这个状态变更每人都需要知道
notify_one()notify_all()
BehaviorWakes one (not guaranteed which)Wakes all
CostLowHigh (all wake up and contend for the lock, only one gets it, the rest go back to sleep—thundering herd)
Used forEach task pushed into a task queueShutdown 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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 错误!虚假唤醒时条件不满足,逻辑错误
cv.wait(ul);
// 直接使用被唤醒后的状态...

// 正确:用带谓词的 wait
cv.wait(ul, [] { return ready; });

// 或者等价的 while 循环写法(wait 内部就是这样做的)
while (!ready) {
    cv.wait(ul);
}

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// 生产者:先锁,改条件,解锁,再通知
{
    lock_guard lg(mtx);
    ready = true;  // 在锁的保护下修改条件
}
cv.notify_one();   // 通知放在解锁之后(性能更好)

// 消费者:wait 会在检查谓词为 true 时直接返回,不进入等待
unique_lock ul(mtx);
cv.wait(ul, [] { return ready; });  // 先检查谓词,true 就不等

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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
unique_lock ul(mtx);
if (cv.wait_for(ul, 100ms, [] { return ready; })) {
    // 条件成立
} else {
    // 超时——可以做超时处理,比如打日志、检查心跳
}

auto deadline = chrono::steady_clock::now() + 5s;
if (cv.wait_until(ul, deadline, [] { return ready; })) {
    // ...
}

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

PitfallConsequenceCorrect Approach
Using if instead of while / no predicateSpurious wakeup causes inconsistent stateAlways use a predicate
notify before modifying the conditionLost wakeup (consumer may wait forever)Modify the condition first, then notify
Mixing different conditions on the same cvA thread is woken by an event it should not care aboutUse different cvs for different conditions
Threads still waiting during destructionUndefined behaviornotify_all + join threads before destroying the cv
Exception thrown inside waitMutex state is uncertainDo 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:

cpp
1
2
3
4
5
6
7
8
9
atomic<int> counter{0};

void increment() {
    counter.fetch_add(1, memory_order_relaxed);  // 原子自增
}

int get() {
    return counter.load(memory_order_acquire);    // 原子读取
}

The key point is Memory Order—it controls the visibility ordering of ordinary memory accesses around atomic operations:

Memory OrderMeaningCost
relaxedGuarantees atomicity only, not orderingLightest, equivalent to ordinary atomic instructions
acquireSubsequent reads/writes cannot be reordered before itRead-side barrier
releasePreceding reads/writes cannot be reordered after itWrite-side barrier
acq_relCombines acquire + releaseFor RMW operations
seq_cstGlobal 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:

cpp
1
2
3
4
5
6
7
8
once_flag init_flag;
ExpensiveResource* resource = nullptr;

void init() {
    call_once(init_flag, [] {
        resource = new ExpensiveResource();
    });
}

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:

1
2
latch:  一次性倒计时 → 数到 0 就永久打开,不能重置
barrier: 可复用 → 每个阶段到齐后自动重置,进入下一轮

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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <latch>
#include <thread>
#include <vector>
using namespace std;

latch init_done(3);  // 3 个线程都初始化完才开门

struct GameModule {
    int id;
    void init() {
        // 每个模块独立的初始化工作(读配置、建立连接……)
        this_thread::sleep_for(chrono::milliseconds(id * 100));
        printf("module %d init done\n", id);
        init_done.arrive_and_wait();  // 报告完成,等其他人
    }
};

int main() {
    vector<thread> threads;
    for (int i = 0; i < 3; ++i) {
        threads.emplace_back([](int id) {
            GameModule{id}.init();
        }, i);
    }
    // 3 个线程都在 init_done 上挂着……
    // 最后一个到的时候门打开,大家一起往下走
    for (auto& t : threads) t.join();
    printf("all modules ready, server starts!\n");
}

Output (regardless of thread ordering, the last line always comes after all “init done” lines):

1
2
3
4
module 0 init done
module 1 init done
module 2 init done
all modules ready, server starts!

Lighter usage: one-shot wait

cpp
1
2
3
4
5
6
7
8
9
latch done(1);

// 主线程
thread worker([&] {
    do_heavy_work();
    done.count_down();  // 通知:我完成了
});
done.wait();  // 主线程阻塞等 worker 干完
worker.join();

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:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <barrier>
#include <thread>
#include <vector>
using namespace std;

// 4 个工作线程 + 1 个主线程 = 5 个参与者
// 每个阶段结束时的回调:主线程负责聚合
auto on_phase_complete = []() noexcept {
    printf("--- phase complete, aggregating... ---\n");
    // 这里可以做:合并碰撞检测结果、更新 AI 状态、提交渲染命令等
};
barrier sync_point(5, on_phase_complete);

void worker(int id) {
    for (int frame = 0; frame < 3; ++frame) {
        printf("worker %d: frame %d - update physics\n", id, frame);
        sync_point.arrive_and_wait();  // 第 1 阶段:等所有人物理更新完

        printf("worker %d: frame %d - update AI\n", id, frame);
        sync_point.arrive_and_wait();  // 第 2 阶段:等所有人 AI 更新完
    }
}

int main() {
    vector<thread> workers;
    for (int i = 0; i < 4; ++i) {
        workers.emplace_back(worker, i);
    }

    for (int frame = 0; frame < 3; ++frame) {
        sync_point.arrive_and_wait();  // 主线程参与第 1 阶段
        sync_point.arrive_and_wait();  // 主线程参与第 2 阶段
    }

    for (auto& t : workers) t.join();
}

The timeline will be:

1
2
3
4
5
6
帧 0:
  worker 0-3: update physics → 到齐 → [回调:aggregating] → 全部释放
  worker 0-3: update AI      → 到齐 → [回调:aggregating] → 全部释放
帧 1:
  worker 0-3: update physics → 到齐 → [回调:aggregating] → 全部释放
  ...

No manual counting, no manual notification, no need to worry about spurious wakeups—barrier handles it all.

latch vs barrier vs condition_variable

latchbarriercondition_variable
Core semanticsCountdown; opens permanently at 0Phase synchronization; auto-resetCondition wait + notification
Reusable❌ One-shot✅ Unlimited✅
Wait for N threads to arrive✅ Native support✅ Native support❌ Requires manual counting
Phase completion callback❌✅❌
When to useInitialization’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.

cpp
1
2
3
4
5
6
7
thread_local int tls_counter = 0;  // 每个线程有独立的一份

void worker(int id) {
    ++tls_counter;
    printf("thread %d: counter = %d\n", id, tls_counter);
    // 每个线程输出都是 1 —— 互不干扰
}

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
线程 A                          线程 B
  TLS 区域                        TLS 区域
  ┌──────────────┐               ┌──────────────┐
  │ tls_counter  │ = 1           │ tls_counter  │ = 1
  │ 随机种子      │               │ 随机种子      │
  │ 日志缓冲区    │               │ 日志缓冲区    │
  └──────────────┘               └──────────────┘
       ↑                               ↑
       │                               │
  TLS 基址寄存器(如 Windows 的 gs 段寄存器)
  编译器生成的访问指令形如: mov eax, gs:[offset_of_tls_counter]

The specific process:

  1. Compile Time—the compiler recognizes the thread_local variable and places it in a special .tdata / .tbss section rather than an ordinary data section. It also computes the variable’s offset within the thread’s TLS.
  2. 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 gs segment register, Linux uses the fs segment register). The main thread also has its own TLS block.
  3. 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 same offset lands in different physical memory.

In pseudo-assembly, it looks like this:

asm
1
2
3
4
5
6
; 普通全局变量:直接寻址
mov  eax, [global_counter]          ; 所有线程访问同一地址

; thread_local 变量:段寄存器 + 偏移
mov  eax, gs:[0x38]                 ; gs 基址随线程不同而不同
                                     ; offset 0x38 = tls_counter 在 TLS 块内的位置

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 errno is implemented with TLS, so errno is also safe in multithreaded programs

Notes

  • Abusing thread_local causes total memory bloat—1000 threads × 4KB of private data per thread = 4MB extra
  • thread_local objects 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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// async:启动异步任务,返回 future
future<int> f = async(launch::async, [] { return 42; });
int result = f.get();  // 阻塞直到任务完成

// promise:手动设置结果
promise<int> p;
future<int> f2 = p.get_future();
thread t([&p] { p.set_value(100); });  // 另一个线程设置值
int val = f2.get();  // 100
t.join();

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:

ThreadThread PoolCoroutine
SchedulerOS kernel preemptionTask queue + cvUser code actively yield/await
Context-switch cost~µs level (kernel mode)~µs level (still threads)~ns level (pure user mode)
StackAllocated independently per thread (~1MB)Same as aboveShared coroutine frame (~a few KB)
Suitable forArbitrary time-consuming tasksAvoiding frequent thread creation/destructionMassive 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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <mutex>
#include <condition_variable>
#include <queue>
#include <thread>
#include <functional>
#include <vector>
using namespace std;

class ThreadPool {
public:
    explicit ThreadPool(size_t num_threads) : stop_(false) {
        for (size_t i = 0; i < num_threads; ++i) {
            workers_.emplace_back([this] {
                while (true) {
                    function<void()> task;
                    {
                        unique_lock ul(mtx_);
                        // 等任务到了,或者 stop
                        cv_.wait(ul, [this] {
                            return stop_ || !tasks_.empty();
                        });

                        if (stop_ && tasks_.empty()) {
                            return;   // 停机 + 队列空 → 线程退出
                        }

                        task = std::move(tasks_.front());
                        tasks_.pop();
                    }
                    task();  // 不持锁执行!
                }
            });
        }
    }

    ~ThreadPool() {
        {
            lock_guard lg(mtx_);
            stop_ = true;
        }
        cv_.notify_all();
        for (auto& t : workers_) {
            if (t.joinable()) t.join();
        }
    }

    // 提交一个任务到池子里
    void enqueue(function<void()> task) {
        {
            lock_guard lg(mtx_);
            tasks_.push(std::move(task));
        }
        cv_.notify_one();
    }

private:
    vector<thread>      workers_;
    queue<function<void()>> tasks_;
    mutex               mtx_;
    condition_variable  cv_;
    bool                stop_;
};

Although this implementation is only about 50 lines, it contains the core mechanisms of a Thread Pool:

  1. 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
  2. Shared task queue: all threads compete to take tasks from the same tasks_ queue
  3. Suspend when idle: when the queue is empty, cv_.wait() puts threads into a waiting state without consuming CPU time
  4. Graceful shutdown: during destruction, first set the stop_ flag, then notify_all() to wake all threads. Each thread checks stop_ && 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.
  5. Release the lock between task executions: the task() call is outside the unique_lock scope—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

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
ThreadPool pool(4);  // 4 个工作线程

// 投递一批任务
for (int i = 0; i < 100; ++i) {
    pool.enqueue([i] {
        printf("task %d on thread %d\n", i, this_thread::get_id());
        this_thread::sleep_for(10ms);  // 模拟耗时操作
    });
}
// ThreadPool 析构时会等所有任务执行完再退出

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:

ScenarioApproach
Database writesPlayer save persistence → throw into the Thread Pool for asynchronous writes; the main thread does not block
Log persistenceLog buffer accumulates a batch → submit to the Thread Pool for flush
Matchmaking computationReceive a matchmaking request → the Thread Pool computes scores asynchronously and writes them into the match result queue
PathfindingSplit 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 TypeApplicable ScenarioCharacteristics
std::mutexCritical sections with clear read/write operations and medium lock holding timeGeneral-purpose, involves kernel-mode switching
std::shared_mutexReads far outnumber writesConcurrent 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_variableNeed to wait for a condition to be satisfiedWorks with mutex, supports notify
std::atomic + CASSingle-variable Atomic Operations, lock-free queuesExtremely lightweight, difficult to implement correctly

Example spinlock implementation (the C++ standard library does not directly provide std::spinlock):

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class spinlock {
    atomic_flag flag = ATOMIC_FLAG_INIT;
public:
    void lock() {
        while (flag.test_and_set(memory_order_acquire)) {
            // 自旋等待;可加 _mm_pause() / yield() 降低功耗
        }
    }
    void unlock() { flag.clear(memory_order_release); }
};

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.”

This post contains some AI-assisted content, reviewed and edited by the author before publishing.
This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...