example4_timed_lock_attempts.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>
#include <chrono>

std::timed_mutex resource_mutex;

void worker(int id) {
    for (int i = 0; i < 3; ++i) {
        if (resource_mutex.try_lock_for(std::chrono::milliseconds(200))) {
            std::cout << "Thread " << id << " acquired lock.\n";
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            resource_mutex.unlock();
        } else {
            std::cout << "Thread " << id << " couldn't acquire lock.\n";
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

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

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

    return 0;
}
Back to mutex