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?
The fopen() function opens the file whose name is the string pointed to by pathname and associates a stream with it. The argument mode points to a string beginning with one of the following sequences (possibly followed by additional characters, as described below): r Open text file for reading.
fseek and fwrite are thread-safe so you can use them without additional synchronization.
the standard C printf() and scanf() functions use stdio so they are thread-safe.
write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.
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 useflockfile()
andfunlockfile()
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.
fopen()
is reenterable, and you can have as many descriptors pointing to the same file as you like.
What you get as a result of reading/writing from/to the file using multiple descriptors is not a thread safety question, but rather concurrent file access, which in most cases (apart from when the file is read-only) won't work well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With