LearnFrenzy
Sign in Take a free test

Multithreading · Multithreading Programs · Question 8

Read-mostly cache with shared_mutex in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Write a Cache with get() under a shared_lock and put() under a unique_lock; run several reader threads and one writer thread, then report the final values and the total number of reads.

Solution
main.cpp
#include <atomic>
#include <iostream>
#include <map>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <string>
#include <thread>
#include <vector>

class Cache {
    mutable std::shared_mutex m_;
    std::map<std::string, int> data_;
public:
    std::optional<int> get(const std::string& k) const {
        std::shared_lock lock(m_);
        auto it = data_.find(k);
        if (it == data_.end()) return std::nullopt;
        return it->second;
    }
    void put(const std::string& k, int v) { std::unique_lock lock(m_); data_[k] = v; }
};

int main() {
    Cache cache;
    cache.put("visits", 0);
    std::atomic<long> reads{0};
    std::vector<std::thread> pool;
    pool.emplace_back([&] { for (int i = 1; i <= 500; ++i) cache.put("visits", i); cache.put("status", 1); });
    for (int r = 0; r < 3; ++r)
        pool.emplace_back([&] {
            for (int i = 0; i < 2000; ++i)
                if (auto v = cache.get("visits"); v && *v >= 0) ++reads;    // always sees a complete value
        });
    for (auto& t : pool) t.join();
    std::cout << cache.get("visits").value_or(-1) << ' ' << cache.get("status").value_or(-1) << ' ' << reads << '\n';
    return 0;
}

Output Verified by compiling and running

500 1 6000

Readers can hold the shared lock together, so reads scale; the writer waits for exclusive access. Readers may see any intermediate count, but never a torn or half-written map.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links