c++ multi-threading deferred launch
我想知道在哪种情况下需要
据我所知,多线程的目的是另一个线程将在后台处理某些事情或进行计算,并在任务完成时返回一个值。它应该在创建线程后立即开始。话虽如此,为什么我们需要这种类型的延迟启动?
With that being said, why do we need this type of deferred launch?
此问题类似于询问为什么
类似地,即使不是所有任务实际上都已执行,因为该组件无需其他任务即可完成其工作,也可以通过显示所有涉及的任务来更清楚地表达软件组件。当然,可以通过仅在任务真正需要运行之前不表达任务来编写不同的软件。
作为示例,代码可以初始化任务数组,并使用循环对其进行迭代。但是,循环中的早期
您可以将带有标志的程序从多线程切换到单线程,以进行调试。
1 2 3 4 5 6 7 | //const auto launchPolicy = std::launch::async; const auto launchPolicy = std::launch::deferred; void doThings(){ auto fut = async(launchPolicy, []{ thing1(); }); thing2(); fut.wait(); } |
没有
仅在需要操作结果时才可以使用延迟启动。例如,您可以执行以下操作,并且将在调用
1 2 3 4 5 6 7 8 9 10 11 | int SomeFunction() { // .... std::future<int> futLazy = std::async( std::launch::deferred, []{ return SomeComplexOperation(); }); if( GetSomeCondition() ) { // Do something involving futLazy.get() } return 1; } |
在此示例中,仅当