LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 14

Two phases separated by a std::barrier Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 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 <barrier>
#include <iostream>
#include <thread>
#include <vector>

int main() {
    const int n = 3;
    std::vector<int> a(n), b(n);
    int phases = 0;
    std::barrier sync(n, [&]() noexcept { ++phases; });   // completion step: runs once per phase
    std::vector<std::jthread> pool;
    for (int i = 0; i < n; ++i)
        pool.emplace_back([&, i] {
            a[i] = i + 1;                    // phase 1
            sync.arrive_and_wait();
            b[i] = a[0] + a[1] + a[2];       // phase 2 reads everyone's phase-1 result
            sync.arrive_and_wait();
        });
    pool.clear();
    std::cout << b[0] << b[1] << b[2] << ' ' << phases << '\n';
    return 0;
}
  • A 666 2 Correct
  • B 123 2
  • C 666 1
  • D 666 6
Correct Answer: Option A

No thread starts phase 2 until all have finished phase 1, so every b[i] = 1 + 2 + 3. The completion function runs once at the end of each of the two phases.

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