C++ 多线程
std::thread + mutex + lock_guard · 难度:高级 · +20XP
C++ 线程并发
C++11 起标准库直接支持线程,不再依赖 pthread。
创建线程
#include
void worker(int id) { cout << "Worker " << id << endl; }
thread t1(worker, 1);
thread t2(worker, 2);
t1.join(); // 等待线程完成
t2.join();
Mutex 保护共享数据
mutex mtx; int counter = 0;
void increment() {
lock_guard lock(mtx); // RAII:构造时加锁,析构时解锁
counter++;
}
thread t1(increment); thread t2(increment);
lock_guard vs unique_lock
| lock_guard | unique_lock |
|---|---|
| 简单的 RAII 锁 | 可手动解锁/重锁 |
| 不可转移 | 可移动 |
| 适合简单场景 | 配合 condition_variable |