example1_basic_usage.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
#include <iostream>
#include <thread>
#include <shared_mutex>
#include <vector>
#include <chrono>

class ThreadSafeCounter {
private:
    mutable std::shared_mutex mutex_;
    int value_ = 0;

public:
    int get() const {
        std::shared_lock lock(mutex_);
        return value_;
    }

    void increment() {
        std::unique_lock lock(mutex_);
        value_++;
    }
};

int main() {
    ThreadSafeCounter counter;

    auto reader = [&counter](int id) {
        for (int i = 0; i < 3; ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            std::cout << "Reader " << id << " sees value " << counter.get() << std::endl;
        }
    };

    auto writer = [&counter]() {
        for (int i = 0; i < 3; ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            counter.increment();
            std::cout << "Writer incremented value\n";
        }
    };

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

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

    return 0;
}
Back to shared_mutex