Possible Duplicate:
stdout thread-safe in C on Linux?
Say thread1 and thread2 are similar and at the end of their jobs they both printf. Is it thread safe or do they have to lock printf somehow?
Is it related to stdout? What if one does fflush(stdout) after each printf? Does it change anything?
Note that the printf(3S) function is safe to call for a multithreaded program.
It's not thread safe, since the buffer where you sprintf is shared between all threads.
This means there is no need to create mutexes or equivalent mechanisms for yourself; the implementation provides the functions to allow you to control the access to printf() et al in a multi-threaded application.
The standard iostream objects cin , cout , cerr , clog , wcin , wcout , wcerr , and wclog follow the same rules as the other classes, with this exception: it's safe to write to an object from multiple threads.
The POSIX.1 and C-language functions that operate on character streams (represented by pointers to objects of type FILE) are required by POSIX.1c to be implemented in such a way that reentrancy is achieved (see ISO/IEC 9945:1-1996, §8.2).
refer to Thread-safety and POSIX.1
Note: Some functions can be reentrant or non-reentrant, depending on their arguments.
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