Question 16
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 <mutex>
#include <thread>
#include <vector>
struct Wallet { std::mutex m; int coins; };
void move_coins(Wallet& from, Wallet& to, int n) {
std::scoped_lock lock(from.m, to.m);
if (from.coins >= n) { from.coins -= n; to.coins += n; }
}
int main() {
Wallet w[3] = {{{}, 100}, {{}, 100}, {{}, 100}};
std::vector<std::thread> pool;
for (int t = 0; t < 3; ++t)
pool.emplace_back([&w, t] { for (int i = 0; i < 1000; ++i) move_coins(w[t], w[(t + 1) % 3], 1); });
for (auto& th : pool) th.join();
std::cout << w[0].coins + w[1].coins + w[2].coins << '\n';
return 0;
}
- A 300 Correct
- B It varies between runs
- C 0
- D 3000
Correct Answer: Option A
Individual balances depend on timing, but every transfer happens with both wallets locked, so the total is always conserved – and scoped_lock prevents the circular deadlock.
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!