基本同步

可以使用互斥体以及其他同步原语来完成线程同步。标准库提供了几种互斥类型,但最简单的是 std::mutex。要锁定互斥锁,请在其上构造锁定。最简单的锁定类型是 std::lock_guard

std::mutex m;
void worker() {
    std::lock_guard<std::mutex> guard(m); // Acquires a lock on the mutex
    // Synchronized code here
} // the mutex is automatically released when guard goes out of scope

使用 std::lock_guard 时,互斥锁将在锁定对象的整个生命周期内被锁定。如果你需要手动控制区域以进行锁定,请使用 std::unique_lock

std::mutex m;
void worker() {
    // by default, constructing a unique_lock from a mutex will lock the mutex
    // by passing the std::defer_lock as a second argument, we
    // can construct the guard in an unlocked state instead and
    // manually lock later.
    std::unique_lock<std::mutex> guard(m, std::defer_lock);
    // the mutex is not locked yet!
    guard.lock();
    // critical section
    guard.unlock();
    // mutex is again released
}

更多线程同步结构