有什么方法可以从文件 C++ 中自动读取一行

问题描述 投票:0回答:2

我目前正在做一个项目,我有一个大文本文件(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 >> word
)似乎增加指针并分两步读取值,因为我会经常得到:

Item1
Item2
Item3
Item2

回来。

所以我想知道是否有一种方法可以自动读取文件的一行?首先将它加载到一个数组中是行不通的,因为文件太大了,我不想一次加载文件块。

遗憾的是,我找不到任何关于

fstream
getline()
的原子性的信息。如果有
readline()
的原子版本或者甚至是使用锁来实现我想要的东西的简单方法,我洗耳恭听。

c++ multithreading parallel-processing atomic fstream
2个回答
5
投票

正确的方法是锁定文件,这将阻止所有其他进程使用它。请参阅维基百科:文件锁定。这对你来说可能太慢了,因为你一次只读一行。但是,如果您在每次函数调用期间阅读 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;
};

0
投票

首先将它加载到数组中是行不通的,因为文件太大,我不想一次加载文件块。

所以使用内存映射文件。操作系统会按需将文件加载到虚拟内存中,但它对您的代码是透明的,并且比使用流 i/o 更有效,您甚至可能不需要或受益于多线程。

© www.soinside.com 2019 - 2024. All rights reserved.