example3_unique_lock_with_deferred_locking.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
33
34
35
36
37
38
39
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

std::mutex mtx;
int shared_resource = 0;

void worker(int id) {
    std::unique_lock<std::mutex> lock(mtx, std::defer_lock);
    
    // Simulate some work before locking
    std::this_thread::sleep_for(std::chrono::milliseconds(id * 100));
    
    lock.lock();
    shared_resource += id;
    std::cout << "Thread " << id << " added " << id << ". New value: " << shared_resource << std::endl;
    lock.unlock();
    
    // Simulate more work after unlocking
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    
    lock.lock();
    shared_resource *= 2;
    std::cout << "Thread " << id << " doubled. New value: " << shared_resource << std::endl;
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 1; i <= 5; ++i) {
        threads.emplace_back(worker, i);
    }

    for (auto& t : threads) {
        t.join();
    }

    return 0;
}
Back to mutex