自动(launch :: async | launch :: deferred)启动策略的std :: async的语义是什么? [英] What is the semantics of std::async with automatic (launch::async|launch::deferred) launch policy?

查看:49
本文介绍了自动(launch :: async | launch :: deferred)启动策略的std :: async的语义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: async 有两个重载,其中一个使参数 std :: launch policy 显式,而另一个则忽略了此参数.该策略是位掩码,因此可以同时指定 launch :: async | launch :: deferred (或者您可以使用忽略此参数的函数来避免使用该策略).在这种情况下,将自动选择策略,因此不能保证选择.我不知道使用这种未知"标记的原因应该是什么.政策.

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.

首先,您不应该将此策略与 wait 函数一起使用:您可能只是得到 future_status :: deferred 响应,以发现调用此函数是无用.接下来,如果您只打算在某个点上 get 的值,则可以使用默认策略,但是我认为没有理由将此选择保留在系统/库实现中,因为即使 std ::也是如此.launch :: async 可能会优化用于执行的线程数.无论如何,实际明确选择的策略会极大地影响使用模式,而使用通过设计隐藏此信息的功能是很奇怪的.

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?

推荐答案

当您要使用最适合系统的内容时,请使用默认值.

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

永远不要以为 future 会在另一个线程上执行.仅将其用于足够独立的代码,以使其在执行时无关紧要.也许这是我的个人喜好,但我认为这样做会产生讨厌的代码.如果您确实需要线程,请使用线程.

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.

在具有一个核心的小型CPU上,最好的策略可能是在启动时在同一线程中运行 async | deferred 任务.如果您要运行四个任务,那么结果就是一个接一个地运行它们.但是在高端CPU上,它可以一次运行所有四个,从而节省时间.

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.

这篇关于自动(launch :: async | launch :: deferred)启动策略的std :: async的语义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆