LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 16

Money is conserved with scoped_lock transfers Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
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.)

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links