小编tuc*_*ber的帖子

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

我目前正在开发一个项目,我有一个大文本文件(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;
}
Run Code Online (Sandbox Code Playgroud)

getline函数(以及"*wordlist >> word")似乎会增加指针并以2个步骤读取值,因为我会经常得到:

Item1
Item2
Item3
Item2
Run Code Online (Sandbox Code Playgroud)

背部.

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

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

提前致谢!

c++ parallel-processing multithreading fstream atomic

6
推荐指数
1
解决办法
567
查看次数