# **[](https://en.cppreference.com/w/cpp/header/mutex)** provides `std::mutex` for mutual exclusion, and `std::lock_guard` / `std::unique_lock` 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. ## Example This example protects a shared counter with a mutex, having two threads each increment it 100 times safely. ```cpp // compile: g++ -std=c++11 -pthread -o mutexexample mutexexample.cpp // run: ./mutexexample // description: protect shared data with mutex #include #include #include int counter = 0; std::mutex mtx; void increment() { for (int i = 0; i < 100; ++i) { std::lock_guard 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; } ```