Is writing to stdout using printf
thread-safe on Linux? What about using the lower-level write
command?
the standard C printf() and scanf() functions use stdio so they are thread-safe.
They are both thread-safe to the point that your application won't crash if multiple threads call them on the same file descriptor. However, without some application-level locking, whatever is written could be interleaved.
write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.
Roughly speaking, a function is thread safe if invoking it concurrently produces sane results, equivalent to those you get when you invoke it non-concurrently. If a single thread calling read never processes the same data twice, then read is thread safe if two threads calling it also never process the same data twice.
It's not specified by the C standard -- it depends on your implementation of the C standard library. In fact, the C standard doesn't even mention threads at all, since certain systems (e.g. embedded systems) don't have multithreading.
In the GNU implementation (glibc
), most of the higher-level functions in stdio that deal with FILE*
objects are thread-safe. The ones that aren't usually have unlocked
in their names (e.g. getc_unlocked(3)
). However, the thread safety is at a per-function call level: if you make multiple calls to printf(3)
, for example, each of those calls is guaranteed to output atomically, but other threads might print things out between your calls to printf()
. If you want to ensure that a sequence of I/O calls gets output atomically, you can surround them with a pair of flockfile(3)/funlockfile(3)
calls to lock the FILE
handle. Note that these functions are reentrant, so you can safely call printf()
in between them, and that won't result in deadlock even thought printf()
itself makes a call to flockfile()
.
The low-level I/O calls such as write(2)
should be thread-safe, but I'm not 100% sure of that - write()
makes a system call into the kernel to perform I/O. How exactly this happens depends on what kernel you're using. It might be the sysenter
instruction, or the int
(interrupt) instruction on older systems. Once inside the kernel, it's up to the kernel to make sure that the I/O is thread-safe. In a test I just did with the Darwin Kernel Version 8.11.1, write(2)
appears to be thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With