首页 文章

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

提问于
浏览
3

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

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

如果有可能,任何例子都会很棒 . 如果没有,请告诉我,以及解决这个问题的一些方法会很棒 . 我查看了以下链接,除了它对我没有意义:Can multiple threads write into a file simultaneously, if all the threads are writing to different locations?

提前致谢!

2 回答

  • 1

    有多个线程写入同一个文件可能会导致一些严重的麻烦 . 您可以尝试使用临界区来同步写入过程(例如使用OpenMP):

    #pragma omp critical [(name)]
    {
       write_to_file
    }
    

    或使用WinApi:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686908(v=vs.85).aspx

  • 8

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

    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;
    };
    

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

    // 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);
    

    使用此方法,单个对象(类型为 SynchronizedFile )管理文件,并通过此对象管理所有写入 . 现在,为了确保只有一个线程可以使用 write(const string&)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;
    };
    

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

    Note :以上代码段使用C 11结构 . 如果您不能使用C 11,请告诉我们,我们可以查看使用C 98(或其他库/ API)来获得相同的结果 .

相关问题