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

标签 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 >> word”)似乎分两步递增指针并读取值,正如我经常得到的:

Item1
Item2
Item3
Item2

返回。

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

遗憾的是,我找不到任何关于 fstream 和 getline 的原子性的信息。如果有 readline 的原子版本或者甚至是使用锁来实现我想要的东西的简单方法,我会洗耳恭听。

提前致谢!

最佳答案

执行此操作的正确方法是锁定文件,这将阻止所有其他进程使用它。参见 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;
};

关于c++ - 有什么方法可以从文件 C++ 中自动读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40904546/

相关文章:

c++ - C++17中数组索引范围的并行for循环

multithreading - 这个 OpenMP 屏障有什么解决方法吗?

video - 并行化和 H.264(或者可能是任何压缩编解码器)?为什么这么难?

c++ - 有没有办法使全局函数/静态成员函数可调用一次?

c++ - 盈透证券 C++ POS API 示例?

c++ - 给自己一个 std::shared_ptr<std::thread> 。定义或未定义的行为

c++ - condition_variable.notify_all 是否应该被互斥锁覆盖?

c++ - 扩展 typedef struct(兼容 VC++11)

java - 线程在中断或停止后不会停止

java - Java 中的并行读写