Skip to content

std::mutex (C++11)

In a Nutshell

The most basic mutex, allowing only one thread to hold it at any given time, used to protect shared data between threads.

#include <mutex>

Core API Cheat Sheet

OperationSignatureDescription
Constructmutex()Constructs the mutex
Destruct~mutex()Destroys the mutex
Lockvoid lock()Locks the mutex, blocks if unavailable
Try Lockbool try_lock()Tries to lock, returns false immediately if unavailable
Unlockvoid unlock()Unlocks the mutex
Native Handlenative_handle_type native_handle()Returns the implementation-defined native handle

Minimal Example

cpp
#include <iostream>
#include <mutex>
#include <thread>

int counter = 0;
std::mutex m;

void increment() {
    std::lock_guard<std::mutex> lock(m);
    ++counter;
}

int main() {
    std::thread t1(increment);
    std::thread t2(increment);
    t1.join();
    t2.join();
    std::cout << counter << '\n'; // 输出: 2
}

Embedded Suitability: High

  • Usually a zero-overhead abstraction; incurs only atomic operation overhead when uncontended.
  • Non-copyable and non-movable, with a deterministic memory layout.
  • Recommended to use with lock_guard to prevent deadlocks caused by exception paths.
  • Note: In RTOS environments, ensure that the underlying pthread or OS primitives are available.

Compiler Support

GCCClangMSVC
4.43.32010

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05