On this page
  1. std::mutex & std::scoped_lock
  2. Overview
  3. Notes & Pitfalls
  4. Example

std::mutex & std::scoped_lock

Prev: std::jthread | Up: concurrency | Next: std::thread
Rel: RAII & Destructors, std::atomic
Ref: cppreference — std::scoped_lock
Tags: #public #prog #cpp #stdlib #concurrency #tier/core


Overview

std::mutex (<mutex>) provides mutual exclusion for shared state. Never call .lock()/.unlock() manually—always wrap mutexes in RAII lock guards:

Notes & Pitfalls

Example

#include <cassert>
#include <mutex>

int main() {
    std::mutex m;
    int shared = 0;
    {
        std::scoped_lock lock(m);
        shared += 42;
    } // automatically unlocked
    assert(shared == 42);
}

Linked from

Related notes