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
The std::future
returned by async
blocks in the destructor. That means when you reach the }
of
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
is destroyed which in turn calls the destructor offuture
which waits for the thread to finish.
What you need to do is store each future
returned from async
in a separate persistent future
that is declared outside of the for loop.