0

Consider this program:

#include <future>
#include <thread>
#include <chrono>

int main()
{
    int a = 0;

    auto f = std::async(std::launch::async,[&]
    {
        a = 1;
        std::this_thread::sleep_for(std::chrono::seconds(5));
        a = 2;
    });

    auto result = f.wait_for(std::chrono::seconds(1));

    if (result == std::future_status::timeout)
    {
        printf("Function timedout ! %d\n", a);
    }
    else if(result == std::future_status::ready)
    {
        printf("Function finished ! %d\n", a);
    }

    return 0;
}

It works as expected except that program won't exit until asynchronous task finishes. Why ?

Maciej Szpakowski
  • 571
  • 1
  • 7
  • 22
  • Are you saying that when you run this your output is "Function finished? Because I just ran this and got "Function timedout". – Mohamad Elghawi Dec 16 '15 at 16:10
  • No, depending on how long your wait is, it might timeout or finish. What I'm asking is, if it times out, process still waits for it to finish. However, it seems that question posted by Jarod42 makes sense. Process waits because destructor of future object blocks. – Maciej Szpakowski Dec 16 '15 at 16:13
  • In your specific case, there's a direct answer to "Why?", namely that a reference to `int a` is captured, and allowing `a` to be destroyed while the task is still using it would break the world (in C++ parlance, cause "undefined behavior"). – Ben Voigt Dec 16 '15 at 16:36
  • Isn't task being destroyed as well ? – Maciej Szpakowski Dec 16 '15 at 16:49

0 Answers0