Serge Rogatch Serge Rogatch - 3 months ago 23
C Question

Can a program call fflush() on the same FILE* concurrently?

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).

Answer

Streams in C1 are thread-safe2. Functions are required to lock the stream before accessing it3.

The fflush function is thread-safe and may be called from any thread at any time, as long as the stream is an output stream or an update stream4.


1 As per the current standard, which is C11.

2 (Quoted from: ISO/IEC 9899:201x 7.21.3 Streams 7):
"Each stream has an associated lock that is used to prevent data races when multiple threads of execution access a stream, and to restrict the interleaving of stream operations performed by multiple threads. Only one thread may hold this lock at a time. The lock is reentrant: a single thread may hold the lock multiple times at a given time."

3 (Quoted from: ISO/IEC 9899:201x 7.21.3 Streams 8):
"All functions that read, write, position, or query the position of a stream lock the stream before accessing it. They release the lock associated with the stream when the access is complete. reentrant: a single thread may hold the lock multiple times at a given time."

4 (Quoted from: ISO/IEC 9899:201x 7.21.5.2 The fflush function 2):
"If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined."