簡體   English   中英

C ++ - 如何讓多個線程寫入文件

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

我目前正在編寫一個使用線程將字符串寫入文件的c ++程序。 我使用ofstream來編寫這些字符串,我注意到只有一個線程可以訪問該文件。

所以我的問題:有沒有辦法在不同的線程中使用ofstream寫入同一個文件?

如果有可能,任何例子都會很棒。 如果沒有,請告訴我,以及解決這個問題的一些方法會很棒。 我查看了以下鏈接,除了它對我沒有意義: 如果所有線程都寫入不同的位置,多個線程可以同時寫入文件嗎?

提前致謝!

一種方法是創建一個包裝文件的單個對象,然后將此包裝器對象的引用提供給需要寫入該文件的所有對象。 在這個包裝器類中,寫入文件是同步的,這樣只有一個編寫器可以一次提交要寫入的數據(即,一個編寫器將在另一個編寫器之前完成,或者同一個編寫器可以編寫)。 例如:

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

由於看起來寫入文件不是你的問題,我已經離開了開頭並寫信給你實現,但上面的代碼片段顯示了同步寫入的基本結構。 如果您在打開和寫入文件時遇到問題,請告訴我,我可以為您解決這個問題。

注意 :上面的代碼段使用C ++ 11結構。 如果您不能使用C ++ 11,請告訴我們,我們可以使用C ++ 98(或其他庫/ API)來實現相同的結果。

有多個線程寫入同一個文件可能會導致一些嚴重的麻煩。 您可以嘗試使用臨界區來同步寫入過程(例如使用OpenMP):

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

或使用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