Search code examples
c++openmpfstream

Is there any possibility of getting some performance gain on fstream (file read) by using openMP


I would like to know whether there might be any possibility of some performance gain on file read by using openMP.

Example code,

fstream file;

file.open("test.txt",ios::in);

file.seekg(0,ios::end);

int len = file.tellg();

char *arr = new char[len];

char *temp = new char[1];

int i;

#pragma omp parallel for shared(arr, len) private(temp, i)
for(i = 0; i < len; i++)
{
    file.seekg(i);
    file.read(temp,1);
    arr[i] = temp[0];
}

I guess using multiple threads for I/O operation is a bad option because finally file read operation will be serialized. But still, I would like to whether one can expect a performance gain. Moreover, I would also like to know how does openMP handles the parallel file read operations.


Solution

  • As you mentioned, you're not likely to get any speedup parallelizing any sort of I/O bound task like this. However, there is a much bigger problem. The code isn't even correct.

    The seekg() and read() methods modify the file variable. So your iterations aren't independent. So you will have race conditions on the stream. In other words, the loop isn't parallelizable.

    So don't expect that code to work at all - let alone with better performance.