LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 6

Passing a value between threads with promise and future Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 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 <future>
#include <iostream>
#include <string>
#include <thread>

int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();
    std::thread worker([&p] {
        int answer = 6 * 7;
        p.set_value(answer);
    });
    std::cout << "waiting... ";
    std::cout << f.get() << '\n';
    worker.join();
    return 0;
}
  • A waiting... 42 Correct
  • B 42 waiting...
  • C waiting... 0
  • D It varies between runs
Correct Answer: Option A

Only the main thread prints; get() blocks until the worker has set the value, so the output is always the same.

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