Mutex_locks
Mutexes and Locking
Section titled “Mutexes and Locking”When multiple threads access shared data, we need synchronization. This chapter covers mutexes and locks.
std::mutex
Section titled “std::mutex”#include <mutex>
int counter = 0;std::mutex mtx;
void increment() { mtx.lock(); counter++; mtx.unlock();}std::lock_guard (RAII)
Section titled “std::lock_guard (RAII)”Automatically locks and unlocks:
#include <mutex>
int counter = 0;std::mutex mtx;
void increment() { std::lock_guard<std::mutex> lock(mtx); counter++; // Automatically unlocked when lock goes out of scope}std::unique_lock
Section titled “std::unique_lock”More flexible than lock_guard:
std::unique_lock<std::mutex> lock(mtx);lock.lock();lock.unlock();lock.try_lock();
// Can release lock earlylock.release();
// Can transfer ownershipstd::unique_lock<std::mutex> lock2 = std::move(lock);Deadlock Prevention
Section titled “Deadlock Prevention”// Bad: Lock in different orders in different threadsvoid thread1() { std::lock_guard<std::mutex> lock1(mutex1); std::lock_guard<std::mutex> lock2(mutex2);}
void thread2() { std::lock_guard<std::mutex> lock2(mutex2); std::lock_guard<std::mutex> lock1(mutex1); // Deadlock!}
// Good: Lock in same ordervoid thread1() { std::lock_guard<std::mutex> lock1(mutex1); std::lock_guard<std::mutex> lock2(mutex2);}Timed Mutex
Section titled “Timed Mutex”std::timed_mutex mtx;
if (mtx.try_lock_for(std::chrono::milliseconds(100))) { // Successfully locked mtx.unlock();} else { // Couldn't acquire lock}Key Takeaways
Section titled “Key Takeaways”- Use mutexes to protect shared data
- Prefer
lock_guardorunique_lockover rawlock/unlock - Avoid deadlock by consistent lock ordering
- Use timed mutexes to avoid indefinite waiting