std::异步函数串行运行
std::async function running serially
当在 for 循环中使用 std::async 和 launch::async 时,我的代码在同一线程中串行运行,就好像每个异步调用在启动之前都等待前一个调用。在 std::async 引用 (std::async( 的注释中,如果 std::future 未绑定到引用,这是可能的,但我的代码并非如此。谁能弄清楚它为什么串行运行?
这是我的代码片段:
class __DownloadItem__ { //DownloadItem is just a "typedef shared_ptr<__DownloadItem__> DownloadItem"
std::string buffer;
time_t last_access;
std::shared_future<std::string> future;
}
for(uint64_t start: chunksToDownload){
DownloadItem cache = std::make_shared<__DownloadItem__>();
cache->last_access = time(NULL);
cache->future =
std::async(std::launch::async, &FileIO::download, this, api,cache, cacheName, start, start + BLOCK_DOWNLOAD_SIZE - 1);
}
}
未来存储在共享的未来中,因为多个线程可能正在等待同一个未来。
我也在使用GCC 6.2.1来编译它。
>析构函数中的async
块返回的std::future
。 这意味着当您}
达到
for(uint64_t start: chunksToDownload){
DownloadItem cache = std::make_shared<__DownloadItem__>();
cache->last_access = time(NULL);
cache->future =
std::async(std::launch::async, &FileIO::download, this, api,cache, cacheName, start, start + BLOCK_DOWNLOAD_SIZE - 1);
} // <-- When we get here
cache
被销毁,这反过来又调用等待线程完成的future
析构函数。
您需要做的是从async
返回的每个future
存储在 for 循环外部声明的单独持久future
中。
这是
C++11定义的std::async
的错误特征。其期货的破坏者很特殊,等待操作完成。更多詳情請參閱Scott's Meyers博客。
cache
在每个循环迭代结束时被销毁,从而调用其子对象的析构函数。
使用 packaged_task
或确保保留指向cache
的共享指针副本的容器,以避免等待析构函数。就个人而言,我会选择packeged_task
正如您自己注意到的那样,future
的future
d-tor 返回 std::async
块并等待异步操作完成(让future
变得ready
(。在您的情况下,cache
对象在每次循环迭代中都超出了范围,因此与它所持有的future
一起被破坏,因此您会看到上述效果。
相关文章:
- 无法获取菜单选择以运行函数.C++
- 为什么std::async使用同一个线程运行函数
- MINGW - 正确运行函数所需的 cdecl
- 如何在 C 中使用空的 main() 方法运行函数?
- 运行函数作为 constexpr 和不作为 constexpr
- 如何在全局变量的构造函数之前运行函数
- 在 Cap'n Proto RPC 服务器中定期运行函数
- 为什么当我在 c++ 中运行函数时,我的代码显示数字 53
- CLang:在 std::thread 中运行函数会导致结构创建BAD_ACCESS
- 如何使用 TBB 在单个线程中运行函数
- 我在运行函数 GetVolumeInformation() 时得到非常随机的结果
- 如何使用 boost::asio io_service 运行函数异步
- Qt - 在其他线程上运行函数
- 在一组模板化对象上运行函数
- pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
- 添加按钮以通知运行函数的通知
- 如何在程序后台运行函数(特别是自动保存函数)?QT / C++
- Qt - 在单独的线程中运行函数
- 如何在单独的线程上运行函数(如果线程可用)
- 如何发出编译和运行C++函数的 LLVM IR