LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 17

Running a packaged_task on a thread Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
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.)

main.cpp
#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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links