Wait for async file write to finish before exiting main thread

Viewed 150

using experimental/filesystem and std::async is there a way to ensure filewrites finish before exiting the main thread?

code used to call the async function

    std::vector<std::future<void>> img_Futures;
    for (int i = 0; i < parsedResult.size(); i++)
    {

        img_Futures.push_back(std::async(std::launch::async, downloadImage, parsedResult[i], baseFolderPath, i));
        

    }

What ends up happening is it writes most of the files, but then there are some files that get left at 0 bytes because (I think) the main thread exits before they have time to write to them.

1 Answers

You can call std::future::wait() on each of the futures. This will block until the future's result is available, i.e. until your downloadImage() function has finished.

Related