Skip to content

std::mutex (C++11)

In a Nutshell

The most basic mutex, allowing only one thread to hold it at a time, used to protect shared data across multiple threads.

#include <mutex>

Core API Quick Reference

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 the mutex, returns false immediately if unavailable
Unlockvoid unlock()Unlocks the mutex
Native handlenative_handle_type native_handle()Returns the underlying 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 Applicability: High

  • Typically a zero-overhead abstraction, incurring only atomic operation overhead when uncontended
  • Non-copyable and non-movable, with a clear and controllable memory layout
  • We recommend using it with lock_guard to avoid deadlocks on exception paths
  • Note: in an RTOS environment, we must 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

Built with VitePress