Skip to content
Advertisement

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?

Advertisement

Answer

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.

Incidentally, if you open the file in append mode (O_APPEND with open(), using "a" with fopen()), then all writes should be at the end of the file, and you should not get into trouble with interleaved writes — unless, perhaps, your independent threads are using file streams and writing more than a buffer-full at a time, or they are using fflush() after writing parts of each line of output, or they are using write() or one of its myriad relatives to write parts of a line each time. There are ways to run into problems even with append mode, but you typically have to be trying to run into them.

Advertisement