C++ - 如何让多个线程写入文件

Fla*_*Cat 5 c++ string multithreading file ofstream

我目前正在编写一个使用线程将字符串写入文件的c ++程序.我使用ofstream来编写这些字符串,我注意到只有一个线程可以访问该文件.

所以我的问题:有没有办法在不同的线程中使用ofstream写入同一个文件?

如果有可能,任何例子都会很棒.如果没有,请告诉我,以及解决这个问题的一些方法会很棒.我查看了以下链接,除了它对我没有意义: 如果所有线程都写入不同的位置,多个线程可以同时写入文件吗?

提前致谢!

Jus*_*ano 13

一种方法是创建一个包装文件的单个对象,然后将此包装器对象的引用提供给需要写入该文件的所有对象.在这个包装器类中,写入文件是同步的,这样只有一个编写器可以一次提交要写入的数据(即,一个编写器将在另一个编写器之前完成,或者同一个编写器可以编写).例如:

class SynchronizedFile {
public:
    SynchronizedFile (const string& path) : _path(path) {
        // Open file for writing...
    }

    void write (const string& dataToWrite) {
        // Write to the file in a synchronized manner (described below)...
    }

private:
    string _path;
};

class Writer {
public:
    Writer (std::shared_ptr<SynchronizedFile> sf) : _sf(sf) {}

    void someFunctionThatWritesToFile () {
        // Do some work...
        _sf->write("Some data to write...");
    }
private:
    std::shared_ptr<SynchronizedFile> _sf;
};
Run Code Online (Sandbox Code Playgroud)

使用这些编写器的客户端代码类似于以下内容:

// Create the synchronized file
auto synchronizedFile = std::make_shared<SynchronizedFile>("some/file.txt");

// Create the writers using the same synchronized file
Writer writer1(synchronizedFile);
Writer writer2(synchronizedFile);
Run Code Online (Sandbox Code Playgroud)

使用此方法,单个对象(类型SynchronizedFile)管理文件,并通过此对象管理所有写入.现在,为了确保只有一个线程可以使用write(const string&),a std::lock_guard.使用这种锁定机制,该实现SynchronizedFile将类似于:

class SynchronizedFile {
public:
    SynchronizedFile (const string& path) : _path(path) {
        // Open file for writing...
    }

    void write (const string& dataToWrite) {
        // Ensure that only one thread can execute at a time
        std::lock_guard<std::mutex> lock(_writerMutex);

        // Write to the file...
    }

private:
    string _path;
    std::mutex _writerMutex;
};
Run Code Online (Sandbox Code Playgroud)

由于看起来写入文件不是你的问题,我已经离开了开头并写信给你实现,但上面的代码片段显示了同步写入的基本结构.如果您在打开和写入文件时遇到问题,请告诉我,我可以为您解决这个问题.

注意:上面的代码段使用C++ 11结构.如果您不能使用C++ 11,请告诉我们,我们可以使用C++ 98(或其他库/ API)来实现相同的结果.