3

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;
}
Helena
  • 444
  • 2
  • 15
  • What do your own attempts indicate? See also cppreference.com for specs. What is your actual question? Please, read [ask]. As a new user here, also take the [tour]. – Ulrich Eckhardt Feb 04 '22 at 06:35
  • @UlrichEckhardt : I am trying to replicate a scenario where it could proceed to "Main end" as i have some bug to work upon. This is a kind of problem replication but i haven't been able to see a scenario where "Main end" will display before all future results are available. – Helena Feb 04 '22 at 06:41
  • Please, always ask directly about the problem you have. That will make it much easier to actually help you solve that problem. Also please take some time to read [the help pages](http://stackoverflow.com/help), take the SO [tour], read [ask], as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Feb 04 '22 at 06:41
  • 1
    Regarding this specific example, because you don't actually use the results of the async calls, and they don't have any side-effects, [the as-if rule](https://en.cppreference.com/w/cpp/language/as_if) allows the compiler to reorder code so the output might be printed before all async calls have finished. – Some programmer dude Feb 04 '22 at 06:45
  • @Someprogrammerdude : What if i start storing the value of `result.get();` in vector , then will be behavior change? – Helena Feb 04 '22 at 06:47
  • 2
    @Someprogrammerdude However, practically speaking, I do not think that this will ever happen, because the threads might execute IO functions, in which case the order must be maintained again. I don't think compiler analysis is so deep as to determine that threads do not do that. – user17732522 Feb 04 '22 at 06:49
  • 3
    Actually, your program has undefined behavior. You are accessing the same `i` unsynchronized in multiple threads. That is a data race. It should be `=`, not `&` in the lambda capture. – user17732522 Feb 04 '22 at 07:02

0 Answers0