Why std :: async calls a function synchronously even with the specified value std :: launch :: async

The function I pass to std :: async prints the current thread id. Despite a call with the std :: launch :: async flag, it prints the same identifier. This 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();
    }
}

Output: 20936 20936 20936 20936 20936

Environment: VS 2015, W7.

Thank you in advance!

+4
source share
2 answers

In fact, you serialize calls waiting for each one, since the same thread can be reused without violating the specification executed by the std::futurethread other than the caller’s thread

, Caller ThreadId:

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();
    }
}
+4

. . , .

, , :

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

, , async, - , , . , : std::futures std::async .

+3

Source: https://habr.com/ru/post/1658591/


All Articles