example3_timeouts.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <shared_mutex>
#include <thread>
#include <chrono>

class TimedResource {
private:
    mutable std::shared_timed_mutex mutex_;
    int value_ = 0;

public:
    bool try_read(std::chrono::milliseconds timeout) const {
        if (mutex_.try_lock_shared_for(timeout)) {
            std::cout << "Read value: " << value_ << std::endl;
            mutex_.unlock_shared();
            return true;
        }
        return false;
    }

    bool try_write(int new_value, std::chrono::milliseconds timeout) {
        if (mutex_.try_lock_for(timeout)) {
            value_ = new_value;
            std::cout << "Wrote value: " << value_ << std::endl;
            mutex_.unlock();
            return true;
        }
        return false;
    }
};

int main() {
    TimedResource resource;

    auto reader = [&resource](int id) {
        for (int i = 0; i < 3; ++i) {
            if (resource.try_read(std::chrono::milliseconds(50))) {
                std::cout << "Reader " << id << " succeeded\n";
            } else {
                std::cout << "Reader " << id << " timed out\n";
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    };

    auto writer = [&resource](int id) {
        for (int i = 0; i < 2; ++i) {
            if (resource.try_write(id * 10 + i, std::chrono::milliseconds(200))) {
                std::cout << "Writer " << id << " succeeded\n";
            } else {
                std::cout << "Writer " << id << " timed out\n";
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(150));
        }
    };

    std::vector<std::thread> threads;
    threads.emplace_back(writer, 1);
    threads.emplace_back(writer, 2);
    for (int i = 0; i < 3; ++i) {
        threads.emplace_back(reader, i);
    }

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

    return 0;
}
Back to shared_mutex