LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 13

Waiting for all workers with std::latch Answer, explanation & discussion

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

int main() {
    const int n = 4;
    std::vector<int> loaded(n, 0);
    std::latch done(n);
    std::vector<std::jthread> pool;
    for (int i = 0; i < n; ++i)
        pool.emplace_back([&, i] {
            loaded[i] = (i + 1) * 100;
            done.count_down();               // "I am finished"
        });
    done.wait();                             // blocks until the count reaches zero
    int total = 0;
    for (int v : loaded) total += v;         // safe: every worker has counted down after writing
    std::cout << total << ' ' << done.try_wait() << '\n';
    return 0;
}
  • A 1000 1 Correct
  • B 1000 0
  • C 0 1
  • D 400 1
Correct Answer: Option A

count_down() synchronises with wait(), so the main thread sees every write made before it. The latch has reached zero, so try_wait() is true.

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