jeudi 23 juillet 2020

Reading and writing different files in their own threads from my main loop in C++11

I am trying to understand, then, write some code that has to read from, and write to many different files and do so from the main loop of my application. I am hoping to use the C++11 model present in VS 2013.

I don't want to stall the main loop so I am investigating spinning off a thread each time a request to write or read a file is generated.

I've tried many things including using the async keyword which sounds promising. I boiled down some code to a simple example:

#include <future>
#include <iostream>
#include <string>

bool write_file(const std::string filename)
{
    std::cout << "write_file: filename is " << filename << std::endl;

    std::this_thread::sleep_for(std::chrono::milliseconds(2000));

    std::cout << "write_file: written" << std::endl;

    return true;
}

int main(int argc, char* argv[])
{
    const std::string filename = "foo.txt";

    auto write = std::async(std::launch::async, write_file, filename);

    while (true)
    {
        std::cout << "working..." << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        std::cout << "write result is " << write.get() << std::endl;
    }
}

I'm struggling to understand the basics but my expectation would be that this code would constantly print "working..." and interspersed in the output would be the write_file start and end messages. Instead, I see that the write_file thread seems to block the main loop output until the timer expires.

I realize I need to also consider mutex/locking on the code to actually write the file but I would like to understand this bit first.

Thank you if you can point me in the right direction.

Molly.

Aucun commentaire:

Enregistrer un commentaire