gpt4 book ai didi

c++ - std::async 函数串行运行

转载 作者:行者123 更新时间:2023-11-30 00:46:03 34 4
gpt4 key购买 nike

当在 for 循环中使用 std::async 和 launch::async 时,我的代码在同一个线程中连续运行,就好像每个异步调用在启动之前等待前一个。在 std::async 引用 ( std::async ) 的注释中,如果 std::future 未绑定(bind)到引用,这是可能的,但我的代码不是这种情况。任何人都可以弄清楚为什么它连续运行吗?

这是我的代码片段:

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);
}
}

future 被存储在一个共享的 future 中,因为多个线程可能正在等待同一个 future 。

我也在使用 GCC 6.2.1 来编译它。

最佳答案

析构函数中 async block 返回的 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 存储在一个单独的持久性 future 中,该 future 在 for 循环之外声明。

关于c++ - std::async 函数串行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957704/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com