我正在制作一个通过多个线程读取文件数据的函数。每个线程读取不同的文件块,使得整个文件的读取操作由多个线程进行。但我不知道如何为每个线程设置不同的文件指针。
我想要做的是每个线程读取一个特定的文件区域,以便多个线程可以立即读取整个文件。
任何建议表示赞赏,如果有任何逻辑缺陷,请告诉我。
代码到现在
void fstreamExtension::readBytesMultiThreaded (std::vector<char>& vBuff)
{
long long int threadBytes [4] = {0, 0, 0, 0};
//these if else statements calculate how many bytes each thread should read, basically file size in bytes is calculated from fileSize() and divided among threads.
if(this -> fileSize() % 2 == 0)
{
threadBytes[0] = this -> fileSize() / 2;
if(threadBytes[0] % 2 == 0)
{
threadBytes[0] /= 2;
threadBytes[1] = threadBytes[0];
threadBytes[2] = threadBytes[0];
threadBytes[3] = threadBytes[0];
}
else
{
threadBytes[0] = (threadBytes[0] - 1) / 2;
threadBytes[1] = threadBytes[0] + 1;
threadBytes[2] = threadBytes[0];
threadBytes[3] = threadBytes[1];
}
}
else
{
threadBytes[0] = (this -> fileSize() - 1) / 2;
if(threadBytes[0] % 2 == 0)
{
threadBytes[0] /= 2;
threadBytes[1] = threadBytes[0];
threadBytes[2] = threadBytes[0];
threadBytes[3] = threadBytes[0] + 1;
}
else
{
threadBytes[0] = (threadBytes[0] - 1) / 2;
threadBytes[1] = threadBytes[0] + 1;
threadBytes[2] = threadBytes[0] + 1;
threadBytes[3] = threadBytes[0] + 1;
}
}
}
线程读取的数据将组合成一个向量类型的缓冲区,作为函数的参数。
说我在一个文件中有 4 行。
-第 1 行
-第 2 行
-第 3 行
-第 4 行
我想要的是创建四个线程,thread1将读取line1,thread2将读取line2,thread3将读取line3,thread4将读取line4。请注意,我将只使用 4 个线程。
我要问的是每个线程我可能需要将文件指针放在线程必须读取的行的开头。对于 4 个线程同时读取文件,可能需要四个文件指针。所以,我想知道如何为单个文件拥有多个文件指针。
您可以将每一行与一个文件块相关联,读取过程保持不变。
请建议除了多个文件指针之外是否还有其他可用的解决方案。
谢谢!