Can anything bad happen (like undefined behavior, file corruption, etc.) if several threads concurrently call fflush()
on the same FILE*
variable?
Clarification: I don't mean writing the file concurrently. I only mean flushing it concurrently.
The threads do not read or write the file concurrently (they only write the file inside a critical section, one thread at a time). They only flush outside of the critical section, to release the critical section sooner so to let the others do the other work (except file writing).
Though it may happen that one thread is writing the file (inside the critical section), while another thread(s) is flushing the file (outside the critical section).
FILE
s are thread-safe, one negative consequence could be that one thread is forced to wait for another to flush, though that would probably only matter if you require fairly high performance. Using functions likeflockfile
¿orflock
? could conceivably lead to deadlock, but probably not in the case you describe. – MendelsohnFILE*
into a consistent state (flushing everything it has written, and maybe even what the second thread has written - this depends on the race), and then the second thread should ensure that what it has just written gets flushed too. Of course there is a better approach with asynchronous flushing in a dedicated thread, but that's more complex thus out of the scope. – Speechless