Matthewgao Matthewgao - 4 months ago 90x
Linux Question

Is fopen() a thread safe function in Linux?

If I use fopen() call to open a same file in multi-thread, and write data to the file. Should I use a mutex to ensure the data won't be disordered?


If two threads both open the same file with fopen(), they will each have independent file streams (FILE *) backed by independent file descriptors referring to the same file. You can write independently to the two file streams, but the net result on the file will depend on where the threads write and when they flush the file stream. The results are unpredictable unless you control where each thread is writing. The simplest thing is to make sure both threads use the same file stream, but you probably still need to coordinate between the threads. Note that POSIX requires the C functions to give coordinated access to the file stream — see flockfile() which imposes the requirement that

All functions that reference (FILE *) objects, except those with names ending in _unlocked, shall behave as if they use flockfile() and funlockfile() internally to obtain ownership of these (FILE *) objects.

If you open the file in append mode in both threads, then the writes would be safely at the end of the file each time, but you still have to worry about flushing the data before the buffer fills.