LearnFrenzy
Sign in Take a free test

Multithreading · Predict the Output · Question 5

Summing results from several std::async tasks Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 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 <vector>

int triangle(int n) { return n * (n + 1) / 2; }

int main() {
    std::vector<std::future<int>> fs;
    for (int n : {10, 20, 30}) fs.push_back(std::async(std::launch::async, triangle, n));
    int total = 0;
    for (auto& f : fs) total += f.get();
    std::cout << total << ' ' << fs[0].valid() << '\n';
    return 0;
}
  • A 730 0 Correct
  • B 730 1
  • C 60 0
  • D 465 0
Correct Answer: Option A

55 + 210 + 465 = 730. After get(), a std::future is no longer valid – its result has been taken.

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