skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-mutex
This page is read only. You can view the source, but not change it.
# <mutex> **[<mutex>](https://en.cppreference.com/w/cpp/header/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. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top