问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/63164245/what-is-the-semantics-of-stdasync-with-automatic-launchasynclaunchdeferr