Skip to content

std::mutex (C++11) ​

In a Nutshell ​

The most basic kind of mutex: only one thread may hold it at any moment, making it the tool of choice for protecting data shared across threads.

Header File ​

#include <mutex>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructmutex()Constructs the mutex
Destruct~mutex()Destroys the mutex
Lockvoid lock()Locks the mutex; blocks if it is unavailable
Try lockbool try_lock()Attempts to lock; 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 ​

C++
#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'; // Output: 2
}

Embedded Applicability: High ​

  • Typically a zero-overhead abstraction: when uncontended, the only cost is that of an atomic operation
  • Neither copyable nor movable, with an explicit and controllable memory layout
  • Best paired with lock_guard to keep exception paths from causing a deadlock
  • Note: in RTOS environments, make sure the underlying pthread or OS primitives are available

Compiler Support ​

GCCClangMSVC
4.43.32010

See Also ​


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05