Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it thread safe to call printf in threads that run simultaneously? [duplicate]

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?

like image 402
j riv Avatar asked Dec 04 '10 13:12

j riv


People also ask

Is it safe to use printf in multithreaded programs?

Note that the printf(3S) function is safe to call for a multithreaded program.

Is Sprintf thread-safe?

It's not thread safe, since the buffer where you sprintf is shared between all threads.

Does printf need mutex?

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.

Is Cin thread-safe?

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.


1 Answers

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.

like image 63
Huang F. Lei Avatar answered Oct 06 '22 04:10

Huang F. Lei