What is the semantics of std::async with automatic (launch::async|launch::deferred) launch policy?
Asked Answered
R

1

0

The std::async has two overloads, one of them makes the parameter std::launch policy explicit while the other omits this parameter. The policy is a bitmask, so both launch::async|launch::deferred may be specified (or you may avoid the policy using the function that omits this parameter). Under the hood the policy is selected automatically in this case, and the choice is not guaranteed. I wonder what should be the reason of using this "unknown" policy.

First of all, you shouldn't use this policy together with wait functions: you may just get the future_status::deferred response to discover that calling this function was useless. Next, you may use default policy if you plan just to get the value on some point, but I see no reason to leave this selection on the system/library implementation, because even std::launch::async may optimize the number of threads used for the execution. Anyway, the actual explicitly selected policy strongly impacts the pattern of usage, and that is very strange to use the function that hides this information by design.

What may be a practical use case when someone would prefer to leave the policy selection to the system?

Rosati answered 30/7, 2020 at 0:3 Comment(0)
M
0

Use the default when you want to use what is best for the system.

You should never assume that a future executes on another thread. Only use it for code which is independent enough that it doesn't matter when it executes. Maybe that's my personal preference but I think doing otherwise makes for nasty code. If you really needed a thread, then use a thread.

On a small CPU with one core the best policy might be to run your async|deferred task in the same thread as soon as you launch it. If you were going to run four tasks, the effect would be to run them one after the other. But on a high end CPU it can run all four at once and save time.

Mcintire answered 30/7, 2020 at 2:16 Comment(2)
My question is different. I'm not asking what launch policy I should prefer, but what is the use case for the default policy. What is the use case when I should prefer something that is best for the system? If I know for sure that GCC always prefers std::launch::deferred and MSVC always prefers std::launch::async, I would use an explicit policy to avoid ambiguity, otherwise I guess that I don't need the std::async at all.Rosati
@DmitryKuzminov You don't think you can trust the library builders to get it right?Mcintire

© 2022 - 2024 — McMap. All rights reserved.