Alex Koshulyan Alex Koshulyan - 1 month ago 10
C++ Question

Why does std::async call the function synchronously even with the specified std::launch::async flag

The function that I pass to std::async prints the current thread id. Inspite of calling with the std::launch::async flag, it prints the same thead id. It means that it calls the function synchronously. Why?

void PrintThreadId()
{
std::cout << std::this_thread::get_id() << std::endl;
}

int main()
{
for (int i = 0; i < 5; ++i)
{
auto f = std::async(std::launch::async, PrintThreadId);
f.wait();
}
}


The output is:
20936
20936
20936
20936
20936

Environment: VS 2015, W7.

Thank you in advance!

Answer

You actually serialize the calls by waiting for each of them, as such the same thread may be reused without breaking the specification that the std::future is executed by a thread distinct from the caller thread

Wake us up when the following code shows the same Caller ThreadId with the rest of them:

void PrintThreadId()
{
    std::cout << std::this_thread::get_id() << std::endl;
}

int main()
{
    std::cout << "Caller threadId (to be different from any id of the future exec thread): ";
    PrintThreadId();

    for (int i = 0; i < 5; ++i)
    {
        auto f = std::async(std::launch::async, PrintThreadId);
        f.wait();
    }
}