1 year ago

#136041

test-img

Helena

Can code flow move ahead before future get method returns?

Is it possible that "Main end" could get displayed before all result.get(); are returned back in below code snippet (Under any scenario)?

OR "Main end" will always be the last one to appear?

#include <iostream>
#include <vector>
#include <future>
#include <chrono>

using namespace std::chrono;

std::vector<std::future<int>> doParallelProcessing()
{
    std::vector<std::future<int>> v;
    for (int i = 0; i < 10; i++)
    {
        auto ret = std::async(std::launch::async, [&]() {
            std::this_thread::sleep_for(seconds(i + 5));
            return 5;
            });
        v.push_back(std::move(ret));
    }
    return v;
}

int main() {

    std::vector<std::future<int>> results;

    results = doParallelProcessing();

    for (std::future<int>& result : results)
    {
        result.get();
    }

    std::cout << "Main end\n";

    return 0;
}

c++

c++17

threadpool

stdasync

std-future

0 Answers

Your Answer

Accepted video resources