std::mutex — mutual exclusion primitive. Prevents concurrent access to shared data.
1#include <mutex>23std::mutex mtx;4int shared_data = 0;56void increment() {7 std::lock_guard<std::mutex> lock(mtx); // RAII lock8 shared_data++; // Protected9} // Automatically unlocked1011// Deadlock prevention: lock multiple mutexes12std::mutex mtx1, mtx2;1314// BAD — potential deadlock15void bad() {16 std::lock_guard<std::mutex> l1(mtx1);17 std::lock_guard<std::mutex> l2(mtx2); // May deadlock!18}1920// GOOD — atomic lock21void good() {22 std::scoped_lock lock(mtx1, mtx2); // C++1723 // Both locked atomically24}2526// Or std::lock + lock_guard27void also_good() {28 std::lock(mtx1, mtx2);29 std::lock_guard<std::mutex> l1(mtx1, std::adopt_lock);30 std::lock_guard<std::mutex> l2(mtx2, std::adopt_lock);31}
Lock types: