LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 2

Each thread writing its own vector slot Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 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 <thread>
#include <vector>

int main() {
    std::vector<int> squares(5);
    std::vector<std::thread> pool;
    for (int i = 0; i < 5; ++i)
        pool.emplace_back([&squares, i] { squares[i] = i * i; });    // distinct elements: no race
    for (auto& t : pool) t.join();
    for (int s : squares) std::cout << s << ' ';
    std::cout << '\n';
    return 0;
}
  • A 0 1 4 9 16 Correct
  • B The order varies between runs
  • C 1 4 9 16 25
  • D 0 0 0 0 0
Correct Answer: Option A

The threads finish in any order, but each writes only its own slot, and printing happens after all joins – so the output is fixed.

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