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.)
#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!