views:

204

answers:

2

I have a multithreaded application that is opening and reading the same file (not writing). I am opening a different file descriptor for each thread (but they all point to the same file). Each thread then reads the file and may close it and open it again if EOF is reached. Is this ok? If I perform fclose() on a file descriptor does it affect the other file descritptors that point to the same file?

+3  A: 

That's ok. You can open all times you want the same file and each file descriptor will be independent from each other.

Pablo Santa Cruz
A: 

That should work fine, provided each thread has its own file handle. Since you mention use of fclose(), that suggests you are also using fopen() in each thread and each thread only affects its own FILE * variable.

Is there a problem?

wallyk
Basically, I created a 2-dim array of file pointers (because each thread will read, say, x files), for a total of y threads. so my FILE* array is array[y][x]. For a given thread i, I open a file via fopen(array[i][0]) for example (for file 0). I then read (fread) the file (not all at once though) and do other tasks (no file writing occurs, though). During a read, if EOF is reached, I do fclose and then fopen again. My concern was that, when I fo fclose and fopen, could I in any way affect the other FILE * pointers from the other threads that are pointing to the same file I performed f close o
Gigi
Assuming your `fopen()` is a typo (it should be `array[i][0] = fopen`...), then yes, that will work fine. Provided each thread does not manipulate data belonging to other threads.
wallyk
Thanks. Yes, all the threads are doing to this files are fopen(), fread(), and fclose().
Gigi