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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)