有没有办法以原子方式从文件C ++中读取一行

时间:2016-12-01 07:09:49

标签: c++ multithreading parallel-processing atomic fstream

我目前正在开发一个项目,我有一个大文本文件(15+ GB),我正在尝试在文件的每一行上运行一个函数。为了加快任务速度,我创建了4个线程并试图让它们同时读取文件。这与我的相似:

#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h> 
#include <thread>
#include <fstream>

void simpleFunction(*wordlist){
    string word;
    getline(*wordlist, word);
    cout << word << endl;
}
int main(){
    int max_concurrant_threads = 4;
    ifstream wordlist("filename.txt");
    thread all_threads[max_concurrant_threads];

    for(int i = 0; i < max_concurrant_threads; i++){
        all_threads[i] = thread(simpleFunction,&wordlist);
    }

    for (int i = 0; i < max_concurrant_threads; ++i) {
        all_threads[i].join();
    }
    return 0;
}

getline函数(以及“* wordlist&gt;&gt; word”)似乎会增加指针并按两步读取值,因为我会经常得到:

Item1
Item2
Item3
Item2

回。

所以我想知道是否有办法原子地读取文件的一行?首先将它加载到数组中是行不通的,因为文件太大了,我不希望一次加载文件。

我遗憾地找不到关于fstream和getline原子性的任何内容。如果有一个原始版本的readline甚至是一个简单的方法来使用锁来实现我想要的东西,我都是耳朵。

提前致谢!

1 个答案:

答案 0 :(得分:4)

正确的方法是锁定文件,这会阻止所有其他进程使用它。见Wikipedia: File locking。这对你来说可能太慢了,因为你一次只读一行。但是如果你在每个函数调用期间读取1000或10000行,那么它可能是实现它的最佳方式。

如果没有其他进程访问该文件,并且其他线程无法访问该文件就足够了,您可以使用在访问该文件时锁定的互斥锁。

void simpleFunction(*wordlist){
    static std::mutex io_mutex;
    string word;
    {
        std::lock_guard<std::mutex> lock(io_mutex);
        getline(*wordlist, word);
    }
    cout << word << endl;
}

实现程序的另一种方法是创建一个单独的线程,该线程一直在读取内存中的行,而其他线程将从存储它们的类中请求单行。你需要这样的东西:

class FileReader {
public:
    // This runs in its own thread
    void readingLoop() {
        // read lines to storage, unless there are too many lines already
    }

    // This is called by other threads
    std::string getline() {
        std::lock_guard<std::mutex> lock(storageMutex);
        // return line from storage, and delete it
    }
private:
    std::mutex storageMutex;
    std::deque<std::string> storage;
};