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?
相关问题
- Multiple sockets for clients to connect to
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- How to let a thread communicate with another activ
- glDrawElements only draws half a quad
As far as I know you should use
mutexes
.I hadn't try this is
C
, but inJava
if you open afile
in more than onethread
, boththreads
can write in it andfile
is really messed up.So I think the situation in
C
will be equivalent toJava
.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 — seeflockfile()
which imposes the requirement thatIf 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.
Below is a thread safe open file write you can open multiple files and it just write to the file sequentially. I think the below code can be still optimized with time sync and popping out unused files to maintain cache
Any suggestion is welcome
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.