Question 19
Back to Exercise
What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <vector>
class PriceTable {
mutable std::shared_mutex m_;
std::map<std::string, int> prices_{{"pen", 20}, {"ink", 45}};
public:
int get(const std::string& k) const { std::shared_lock lock(m_); return prices_.at(k); }
void raise(const std::string& k, int by) { std::unique_lock lock(m_); prices_[k] += by; }
};
int main() {
PriceTable t;
std::vector<long> read_sum(4, 0);
std::vector<std::thread> pool;
pool.emplace_back([&t] { for (int i = 0; i < 10; ++i) t.raise("pen", 1); });
for (int r = 0; r < 3; ++r)
pool.emplace_back([&t, &read_sum, r] { for (int i = 0; i < 100; ++i) read_sum[r] += t.get("ink"); });
for (auto& th : pool) th.join();
std::cout << t.get("pen") << ' ' << read_sum[0] << ' ' << read_sum[1] << ' ' << read_sum[2] << '\n';
return 0;
}
- A 30 4500 4500 4500 Correct
- B 20 4500 4500 4500
- C 30 450 450 450
- D It varies between runs
Correct Answer: Option A
Readers share the lock and never see a half-done write; the writer is exclusive. Only "pen" changes, so every reader sums 100 × 45.
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!