LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 3

A counter protected by a mutex Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 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>

int main() {
    int total = 0;
    std::mutex m;
    std::vector<std::thread> pool;
    for (int t = 1; t <= 3; ++t)
        pool.emplace_back([&, t] {
            for (int i = 0; i < 1000; ++i) {
                std::lock_guard lock(m);
                total += t;
            }
        });
    for (auto& th : pool) th.join();
    std::cout << total << '\n';
    return 0;
}
  • A 6000 Correct
  • B 3000
  • C 1000
  • D It varies between runs
Correct Answer: Option A

The mutex makes every update complete before the next: 1000 × (1 + 2 + 3).

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