example2_threadsafe_cache.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
#include <iostream>
#include <unordered_map>
#include <shared_mutex>
#include <thread>
#include <vector>

class ThreadSafeCache {
private:
    mutable std::shared_mutex mutex_;
    std::unordered_map<int, std::string> cache_;

public:
    std::string get(int key) const {
        std::shared_lock lock(mutex_);
        auto it = cache_.find(key);
        if (it != cache_.end()) {
            return it->second;
        }
        return "Not found";
    }

    void set(int key, const std::string& value) {
        std::unique_lock lock(mutex_);
        cache_[key] = value;
    }
};

int main() {
    ThreadSafeCache cache;

    auto reader = [&cache](int id) {
        for (int i = 0; i < 5; ++i) {
            std::cout << "Reader " << id << " gets: " << cache.get(i % 3) << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }
    };

    auto writer = [&cache](int id) {
        for (int i = 0; i < 3; ++i) {
            cache.set(i, "Value " + std::to_string(id) + "-" + std::to_string(i));
            std::cout << "Writer " << id << " set value for key " << i << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    };

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

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

    return 0;
}
Back to shared_mutex