sflee
sflee

Reputation: 1719

Why std::future not blocking

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?

Upvotes: 1

Views: 213

Answers (1)

Rakete1111
Rakete1111

Reputation: 49028

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).

Upvotes: 3

Related Questions