LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 11

std::jthread joins in its destructor Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 11 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<long> sums(3);
    {
        std::vector<std::jthread> workers;
        for (int i = 0; i < 3; ++i)
            workers.emplace_back([&sums, i] { for (int k = 1; k <= 100 * (i + 1); ++k) sums[i] += k; });
    }   // all jthreads are joined here – no explicit join, no terminate
    std::cout << sums[0] << ' ' << sums[1] << ' ' << sums[2] << '\n';
    return 0;
}
  • A 5050 20100 45150 Correct
  • B 5050 5050 5050
  • C 0 0 0
  • D The program terminates
Correct Answer: Option A

Destroying the vector destroys the jthreads, and each joins – so the sums are complete before they are printed.

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