Mutexes

std::mutex and lock guards

Interview Relevant: Synchronization

Mutexes

Protect shared data from concurrent access.

Code Examples

Mutex synchronization for thread safety.

cpp
1#include <mutex>
2
3mutex mtx;
4int counter = 0;
5
6void increment() {
7    mtx.lock();
8    counter++;
9    mtx.unlock();
10}
11
12// RAII with lock_guard (preferred)
13void safeIncrement() {
14    lock_guard<mutex> lock(mtx);
15    counter++;
16}  // Automatically unlocked
17
18// unique_lock - more flexible
19void flexibleLock() {
20    unique_lock<mutex> lock(mtx);
21    counter++;
22    lock.unlock();  // Can unlock manually
23    // Do other work...
24    lock.lock();    // Re-lock
25}
26
27// Try to lock without blocking
28if (mtx.try_lock()) {
29    counter++;
30    mtx.unlock();
31}
32
33// Lock multiple mutexes (avoid deadlock)
34mutex m1, m2;
35void safe() {
36    scoped_lock lock(m1, m2);  // C++17
37    // or
38    lock(m1, m2);  // Lock both
39    lock_guard<mutex> lg1(m1, adopt_lock);
40    lock_guard<mutex> lg2(m2, adopt_lock);
41}
42
43// Recursive mutex (same thread can lock multiple times)
44recursive_mutex recMtx;

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In