When using std::async with launch::async in a for loop, my code runs serially in the same thread, as if each async call waits for the previous before launching. In the notes for std::async references (std::async), this is possible if the std::future is not bound to a reference, but that's not the case with my code. Can anyone figure out why it's running serially?
Here is my code snippet:
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);
}
}
The future is being stored in a shared future because multiple threads might be waiting on the same future.
I'm also using GCC 6.2.1 to compile it.
cache
you add to the containers is not thecache
that has the future stored in it. – NathanOliverstd::shared_future
is for multiple threads waiting on one result whereas I think you need one thread waiting on multiple results. Maybe you needstd::vector<std::future>
? – Galikcache
variable is not the samecache
in the container ifcache
is ashared_ptr
. Can you please clarify? – thejinx0r