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