CKTIS / C++
std::mutex — mutual exclusion between threads
std::mutex from <mutex> allows only one thread at a time to own its lock. It protects shared data when all conflicting accesses follow the same locking protocol. std::lock_guard manages lock release within a scope.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <mutex>
std::mutex m;
std::lock_guard<std::mutex> guard(m);std::mutex from <mutex> provides exclusive, non-recursive lock ownership. A critical section is code executed while holding that ownership. A mutex does not protect data automatically: all potentially conflicting accesses must follow the same synchronization protocol.
lock() waits to acquire ownership. try_lock() does not wait and reports success; it may return false even for an available mutex. unlock() releases ownership and may be called only by the owner. Releasing synchronizes with a later successful acquisition of the same mutex, making earlier writes visible.
Prefer a named std::lock_guard<std::mutex> object: its constructor locks the mutex, and its destructor unlocks it, including when an exception exits the scope. The mutex must outlive the guard. Do not try to reacquire a std::mutex you already own; it does not support recursion. It cannot be copied or moved, and destroying an owned mutex causes undefined behavior.
In the example, two threads increment counter under the same lock. Each call to join() waits only for the thread represented by the object on which it is called. The example calls first.join() and second.join() to wait for each thread separately before reading the counter, so the result is 2000 regardless of their execution order. The example uses facilities available in C++23; the specified compilation standard does not attest to a production runtime. The referenced source is an evolving standard draft, not a frozen C++23 edition.
Examples
#include <iostream>
#include <mutex>
#include <thread>
int main() {
std::mutex m;
int counter = 0;
auto increment = [&] {
for (int i = 0; i < 1000; ++i) {
std::lock_guard<std::mutex> guard(m);
++counter;
}
};
std::thread first(increment);
std::thread second(increment);
first.join();
second.join();
std::cout << counter << '\n';
}
Result
2000
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.