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
2010-04-18 21:05:32
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
2010-04-18 21:06:09
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
2010-04-18 21:19:37
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
2010-04-18 22:07:04
Thanks. Yes, all the threads are doing to this files are fopen(), fread(), and fclose().
Gigi
2010-04-18 22:56:42