It is not specified by the C standard - it depends on your implementation of the C standard library. In fact, the C standard does not even mention threads at all, since some systems (for example, embedded systems) do not have multithreading.
In the GNU implementation ( glibc ), most of the top-level functions in stdio that deal with FILE* objects are thread safe. Those that usually do not have unlocked in their names (e.g. getc_unlocked(3) ). However, thread safety depends on the call level for each function: if you make several calls to printf(3) , for example, each of these calls is guaranteed to be output atomically, but other threads can print things between your calls before printf() . If you want the I / O call sequence to be output atomically, you can surround them with a pair of flockfile(3)/funlockfile(3) calls to block the FILE descriptor. Note that these functions are reentrant, so you can safely call printf() between them, and this will not lead to a deadlock, even the thought of printf() itself makes a call to flockfile() .
Low-level I / O calls, such as write(2) , should be thread safe, but I'm not 100% sure - write() makes a system call in the kernel to do I / O. How exactly this happens depends on which kernel you use. This can be a sysenter command or an int (interrupt) statement for older systems. Once inside the kernel, up to the kernel to make sure I / O is thread safe. In the test that I just did with Darwin's kernel version 8.11.1, write(2) seems thread safe.
Adam Rosenfield Jan 22 '09 at 5:07 2009-01-22 05:07
source share