[英]Is there any way to atomically read a line from a file 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;
}
getline函数(以及“ * wordlist >> word”)似乎增加了指针并分两步读取值,因为我会定期得到:
Item1 Item2 Item3 Item2
背部。
所以我想知道是否有一种方法可以自动读取文件的一行? 首先将其加载到数组中是不可行的,因为文件太大,我宁愿不要一次将文件分块加载。
可悲的是,我找不到关于fstream和getline原子性的任何信息。 如果有readline的原子版本,或者甚至有简单的使用锁来实现我想要的方法的方法,我都会耳熟能详。
提前致谢!
正确的方法是锁定文件,这将阻止所有其他进程使用该文件。 请参阅Wikipedia:文件锁定 。 这可能对您来说太慢了,因为您一次只能读一行。 但是,如果在每个函数调用期间读取例如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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.