LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 9

std::call_once runs initialisation exactly once Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 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 <atomic>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

std::once_flag init_flag;
std::atomic<int> init_runs{0};
int config = 0;

void use_config(std::vector<int>& seen, int i) {
    std::call_once(init_flag, [] { ++init_runs; config = 42; });    // the first caller runs it, others wait
    seen[i] = config;
}

int main() {
    std::vector<int> seen(8);
    std::vector<std::thread> pool;
    for (int i = 0; i < 8; ++i) pool.emplace_back(use_config, std::ref(seen), i);
    for (auto& t : pool) t.join();
    bool all42 = true;
    for (int v : seen) all42 = all42 && v == 42;
    std::cout << init_runs << ' ' << all42 << '\n';
    return 0;
}
  • A 1 1 Correct
  • B 8 1
  • C 1 0
  • D It varies between runs
Correct Answer: Option A

call_once guarantees one execution, and every other caller waits until it has finished – so all of them see 42.

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