基本同步

可以使用互斥體以及其他同步原語來完成執行緒同步。標準庫提供了幾種互斥型別,但最簡單的是 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
}

更多執行緒同步結構