the*_*x0r 1 c++ multithreading asynchronous future c++11
当在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);
}
}
Run Code Online (Sandbox Code Playgroud)
未来将存储在共享的未来,因为多个线程可能正在等待同一个未来.
我也在使用GCC 6.2.1来编译它.
将std::future通过返回async在析构函数块.这意味着当你到达}时
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
Run Code Online (Sandbox Code Playgroud)
cache被销毁,然后调用析构函数future等待线程完成.
您需要做的是将每个future返回的内容存储async在一个future在for循环之外声明的单独的持久性中.