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

耗尽温柔 提交于 2021-01-29 15:46:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!