example1_safely_lock_multiple_mutexes.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mutex1;
std::mutex mutex2;

void threadFunction1() {
    for (int i = 0; i < 5; ++i) {
        std::scoped_lock lock(mutex1, mutex2);  // Lock both mutexes safely
        std::cout << "Thread 1 is executing with locks on both mutex1 and mutex2" << std::endl;
        // Critical section protected by both mutexes
    }
}

void threadFunction2() {
    for (int i = 0; i < 5; ++i) {
        std::scoped_lock lock(mutex1, mutex2);  // Lock both mutexes safely
        std::cout << "Thread 2 is executing with locks on both mutex1 and mutex2" << std::endl;
        // Critical section protected by both mutexes
    }
}

int main() {
    std::thread t1(threadFunction1);
    std::thread t2(threadFunction2);

    t1.join();
    t2.join();

    return 0;
}
Back to std_scoped_lock