当前位置:网站首页>Item 36: Specify std::launch::async if asynchronicity is essential.
Item 36: Specify std::launch::async if asynchronicity is essential.
2022-08-01 00:32:00 【loongknown】
Item 36: Specify std::launch::async if asynchronicity is essential.
当你使用 std::async() When executing a function or callable object,You usually expect this function to be executed asynchronously.但是, std::async() Not necessarily as you wish.其实 std::async() It is based on the execution strategy to decide whether to execute asynchronously. std::async() There are two execution strategies,定义在 std::launch 作用域中:
std::launch::asyncThe function or executable object must execute asynchronously,That is, running on other threads.std::launch::deferredThe function or executable object is executed lazily.仅在std::async()的返回对象std::future调用get或wait时,It is executed synchronously in the current thread,And the caller blocks until the function execution completes.
std::async() The default strategy is actually a combination of the two,That is, the following two have the same meaning:
auto fut1 = std::async(f); // run f using default launch policy
auto fut2 = std::async(std::launch::async | // run f either
std::launch::deferred, // async or
f); // deferred
under the default policy,f It may be executed synchronously or asynchronously.正如 Item 35: Prefer task-based programming to thread-based. 中讨论的:The thread management module of the standard library is responsible for the creation and release of threads,Oversubscription can be effectively avoided、保证负载均衡.This is extremely convenient std::async 的使用.
但是,The default strategy also has the following problems:
- 无法预测
fWhether to execute concurrently. - 无法预测
f是否运行在get或waiton the thread at the time of the call. - Not even predictable
f是否已经执行了.Because there is no guarantee that it will be calledget或wait.
当 f To access thread-local storage(TLS,Thread Local Storage)时,It is impossible to predict which thread's local storage is being accessed.
auto fut = std::async(f); // TLS for f possibly for
// independent thread, but
// possibly for thread
// invoking get or wait on fut
std::async The default policy of wait_for Timeout call writing,可能导致 bug,例如:
using namespace std::literals; // for C++14 duration suffixes; see Item 34
void f() // f sleeps for 1 second, then returns
{
std::this_thread::sleep_for(1s);
}
auto fut = std::async(f); // run f asynchronously (conceptually)
while (fut.wait_for(100ms) != // loop until f has
std::future_status::ready) // finished running...
{
// which may never happen!
…
}
如果 std::async 是并发执行,That is, the execution strategy is std::launch::async,以上代码没有问题.但是,如果执行策略为 std::launch::deferred时,fut.wait_for 总是返回 future_status::deferred,There is a problem with the above code.解决办法也很简单,先通过 wait_for 的超时时间为 0 来检测 std::async 是异步执行还是同步执行:
auto fut = std::async(f); // as above
if (fut.wait_for(0s) == // if task is
std::future_status::deferred) // deferred...
{
// ...use wait or get on fut
… // to call f synchronously
} else {
// task isn't deferred
while (fut.wait_for(100ms) != // infinite loop not
std::future_status::ready) {
// possible (assuming
// f finishes)
… // task is neither deferred nor ready,
// so do concurrent work until it's ready
}
… // fut is ready
}
综上,If your usage scenario is not the following,Then you need to consider whether you need to replace it std::async 的默认策略:
- 当调用
get或wait时,Tasks do not need to be executed concurrently. - It doesn't care which thread's local storage is being accessed.
- 可以保证
get或wait一定会被调用,Or it is acceptable for the task not to be executed. - 使用
wait_for或wait_until时,需要考虑std::launch::deferred策略.
If not the above scenario,You may need to specify use std::launch::async 策略,That is, a thread is actually created to execute tasks concurrently:
auto fut = std::async(std::launch::async, f); // launch f asynchronously
This provides a wrapper for concurrently executing tasks:
template<typename F, typename... Ts> // C++11
inline
std::future<typename std::result_of<F(Ts...)>::type>
reallyAsync(F&& f, Ts&&... params) // return future
{
// for asynchronous
return std::async(std::launch::async, // call to f(params...)
std::forward<F>(f),
std::forward<Ts>(params)...);
}
reallyAsync Accepts an executable object f 和 多个参数 params,and perfectly forwarded to std::async ,同时使用 std::launch::async 策略.C++14 版本如下:
template<typename F, typename... Ts>
inline
auto // C++14
reallyAsync(F&& f, Ts&&... params)
{
return std::async(std::launch::async,
std::forward<F>(f),
std::forward<Ts>(params)...);
}
至此,本文结束.
参考:
边栏推荐
- [Microservice] Distributed Transaction Solution - Seata
- An open source and easy-to-use flowchart drawing tool drawio
- [微服务]分布式事务解决方案-Seata
- 命名实体识别-模型:BERT-MRC
- Matlab/Arcgis processing nc data
- qlib量化源码分析:qlib/qlib/contrib/model/gbdt.py
- Unity3D学习笔记10——纹理数组
- Exam preparation plan
- Qlib quantitative source analysis: qlib/qlib/contrib/model/GBDT py
- Inheritance and friend, static member relationship
猜你喜欢

One line of code to solve CoreData managed object properties change in SwiftUI problem of animation effects
Mysql environment installation under Linux (centos)

JVM面试题总结(持续更新中)
![[AMEX] LGBM Optuna美国运通信用卡欺诈赛 kaggle](/img/64/55af53a3d9dc1162490d613fe8a436.png)
[AMEX] LGBM Optuna美国运通信用卡欺诈赛 kaggle

精心总结十三条建议,帮你创建更合适的MySQL索引

游戏安全03:缓冲区溢出攻击简单解释
![[MATLAB project combat] LDPC-BP channel coding](/img/37/4777e4d05cb2dbb1865f1d05ae9878.png)
[MATLAB project combat] LDPC-BP channel coding

Google Earth Engine——Error: Image.clipToBoundsAndScale, argument ‘input‘: Invalid type的错误解决

MYSQL查询截取优化分析

Team of Professor Chen Jianyu of Tsinghua University | Contact Safety Reinforcement Learning Framework Based on Contact-rich Robot Operation
随机推荐
[Microservice] Distributed Transaction Solution - Seata
NIO编程
mySql data view
Luogu P3373: 线段树
清华大学陈建宇教授团队 | 基于接触丰富机器人操作的接触安全强化学习框架
RTL8762DK RTC(五)
游戏安全03:缓冲区溢出攻击简单解释
Carefully summarize thirteen suggestions to help you create more suitable MySQL indexes
ECCV2022 Workshop | 复杂环境中的多目标跟踪和分割
Keil nRF52832下载失败
Binary tree traversal non-recursive program -- using stack to simulate system stack
Inheritance and friend, static member relationship
In 2022, the latest eight Chongqing construction members (electrical construction workers) simulation question bank and answers
vim的基本使用概念
设计消息队列存储消息数据的MySQL表格
声称AI存在意识,谷歌工程师遭解雇:违反保密协议
蓝图:杨辉三角排列
[Cloud Residency Co-Creation] [HCSD Big Celebrity Live Broadcast] Personally teach the secrets of interviews in big factories
MYSQL逻辑架构
浏览器下载快捷方式到桌面(PWA)