C ++-如何使多个线程写入文件 [英] C++ - How to have multiple threads write to a file

查看:772
本文介绍了C ++-如何使多个线程写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently writing a c++ program that uses threads to write strings to a file. 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?

如果可能的话,任何例子都是很好的.如果没有,也请让我知道,解决这个问题的一些方法将是很棒的. 我看了下面的链接,除了对我来说真的没有意义: 可以写入多个线程如果所有线程都写到不同的位置,则同时写入一个文件吗?

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?

提前谢谢!

推荐答案

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

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 (i.e., 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);

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

Using this approach, a single object (of type SynchronizedFile) manages the file and all writing is managed through this object. Now, in order to ensure that only one thread can use the write(const string&), a std::lock_guard. Using this locking mechanism, the implementation for the SynchronizedFile would resemble:

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.

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

Note: The above snippets use C++11 structures. 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 ++-如何使多个线程写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆