简体   繁体   English

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

[英]C++ - How to have multiple threads write to a file

I am currently writing a c++ program that uses threads to write strings to a file. 我目前正在编写一个使用线程将字符串写入文件的c ++程序。 I am using ofstream to write these strings, and I noticed that only one of the threads has access to the file. 我使用ofstream来编写这些字符串,我注意到只有一个线程可以访问该文件。

So my question: Is there any way to use ofstream in different threads to write to the same file? 所以我的问题:有没有办法在不同的线程中使用ofstream写入同一个文件?

If it is possible, any examples would be great. 如果有可能,任何例子都会很棒。 If not, please let me know that as well, and some ways to get around this would be great. 如果没有,请告诉我,以及解决这个问题的一些方法会很棒。 I have looked at the following link, except it didn't really make sense to me: Can multiple threads write into a file simultaneously, if all the threads are writing to different locations? 我查看了以下链接,除了它对我没有意义: 如果所有线程都写入不同的位置,多个线程可以同时写入文件吗?

Thanks in advance! 提前致谢!

One approach is to create a single object that wraps the file and then provide a reference to this wrapper object to all objects that need to write to the file. 一种方法是创建一个包装文件的单个对象,然后将此包装器对象的引用提供给需要写入该文件的所有对象。 Within this wrapper class, writing to the file is synchronized so that only one writer can submit data to be written at a time (ie, one writer will complete before another, or the same writer, can write). 在这个包装器类中,写入文件是同步的,这样只有一个编写器可以一次提交要写入的数据(即,一个编写器将在另一个编写器之前完成,或者同一个编写器可以编写)。 For example: 例如:

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

The client code that uses these writers would resemble the following: 使用这些编写器的客户端代码类似于以下内容:

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

Using this approach, a single object (of type SynchronizedFile ) manages the file and all writing is managed through this object. 使用此方法,单个对象( SynchronizedFile类型)管理文件,并通过此对象管理所有写入。 Now, in order to ensure that only one thread can use the write(const string&) , a std::lock_guard . 现在,为了确保只有一个线程可以使用write(const string&) ,一个std::lock_guard Using this locking mechanism, the implementation for the SynchronizedFile would resemble: 使用此锁定机制, 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;
};

Since it appears as though writing to a file is not your issue, I have left the opening and writing to you to implement, but the above snippet shows the basic structure for synchronizing the writing. 由于看起来写入文件不是你的问题,我已经离开了开头并写信给你实现,但上面的代码片段显示了同步写入的基本结构。 If you have issues opening and writing to the file, let me know and I can flush that out for you. 如果您在打开和写入文件时遇到问题,请告诉我,我可以为您解决这个问题。

Note : The above snippets use C++11 structures. 注意 :上面的代码段使用C ++ 11结构。 If you cannot use C++11, let me know and we can look at using C++98 (or other libraries/APIs) to achieve the same results. 如果您不能使用C ++ 11,请告诉我们,我们可以使用C ++ 98(或其他库/ API)来实现相同的结果。

Having multiple threads to write to the same file can lead to some serious troubles. 有多个线程写入同一个文件可能会导致一些严重的麻烦。 You can try synchronizing the process of writing, by using critical section, for example(using OpenMP): 您可以尝试使用临界区来同步写入过程(例如使用OpenMP):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM