<mutex> provides std::mutex for mutual exclusion, and std::lock_guard<Mutex> / std::unique_lock<Mutex> for RAII-based locking. Always lock via a lock guard to ensure the lock is released even if an exception is thrown.
Use std::lock_guard for simple cases; use std::unique_lock when you need to unlock before scope end or transfer lock ownership.
This example protects a shared counter with a mutex, having two threads each increment it 100 times safely.
// compile: g++ -std=c++11 -pthread -o mutexexample mutexexample.cpp // run: ./mutexexample // description: protect shared data with mutex #include <mutex> #include <iostream> #include <thread> int counter = 0; std::mutex mtx; void increment() { for (int i = 0; i < 100; ++i) { std::lock_guard<std::mutex> lock(mtx); counter++; } } int main() { std::thread t1(increment); std::thread t2(increment); t1.join(); t2.join(); std::cout << "final counter: " << counter << "\n"; return 0; }