1

I am using VS2013.
I just read this and found that a future should block in its destructor.

I tried some code but the std::future did not block.

void PrintFoo()
{
    while (true)
    {
        std::cout << "Foo" << std::endl;
        Sleep(1000);
    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    {
        auto f = std::async(std::launch::async, PrintFoo);
    }
    while (true)
    {
        Sleep(1000);
        std::cout << "Waiting" << std::endl;
    }
    std::cout << "Before application end" << std::endl;
    return 0;
}

I have the output:

Foo
Waiting
Foo
Waiting

Am I misunderstanding something?

sflee
  • 1,485
  • 4
  • 26
  • 50
  • 2
    VS2017 does not reproduce this behavior. It just keeps printing `Foo`, as expected. – AnT Aug 09 '17 at 02:52

1 Answers1

3

Yes. Your braces around f introduce a new scope, and because f is defined in that scope, it will get destroyed when that scope ends. Which is immediately after, and f will then block. So technically, it should print Foo every second.

The actual output is more interesting though. Your compiler interleaves the two infinite loops, which it isn't allowed to do (because your loop has side effects) since C++11 (I guess VS2013 isn't fully C++11 standards compliant yet).

Rakete1111
  • 42,521
  • 11
  • 108
  • 141