Question 17
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::packaged_task<std::string(std::string, int)> task([](std::string s, int n) {
std::string out;
for (int i = 0; i < n; ++i) out += s;
return out;
});
std::future<std::string> result = task.get_future();
std::thread t(std::move(task), "ab", 3); // the task is move-only
std::cout << result.get() << ' ' << result.valid() << '\n';
t.join();
return 0;
}
- A ababab 0 Correct
- B ababab 1
- C ab 0
- D Compilation error
Correct Answer: Option A
A packaged_task wraps a callable and links its return value to a future; it can be moved into a thread or queued in a thread pool.
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!