Search code examples
clinuxmultithreadingconcurrencymulticore

Are both calls to `fprintf(stdout, ...)` and `fprintf(stderr, ...)` guaranteed to non-interleave with multiple threads?


Say I have two threads that print something (relatively long) either to stderr or stdout, is the function to both these streams thread-safe in the sense that they will never "interleave" characters? So, for example, if I have "Hello, World", I will never get "HHellllo,, WorldWorld" Or whatever other interleaving? This is for x86, GCC, Linux > 3.0.


Solution

  • I took a look at glibc, and each call to vfprintf will call the POSIX flockfile (_IO_flockfile) and funlockfile (_IO_funlockfile) on the stream.

    So, the characters within a call won't get interleaved with characters from a call from another thread as only one thread can hold the lock on stdout or stderr.

    All bets are off as to the ordering of multiple calls across the various threads though.