以前一直担心在多线程环境下,多个线程同时调用 fprintf 往同一个 fp 写东西会不会出现交错的情况,昨天微博上问了问人,有提到 fprintf_unlocked,也说到 fprintf 是线程安全的,后来又查了一下,看到这里,http://stackoverflow.com/quest… ,其中也有提到,fprintf 在多线程下是内部持有锁的
If you’re using a single
FILE
object to perform output on an open file, then wholefprintf
calls on thatFILE
will be atomic, i.e. lock is held on theFILE
for the duration of thefprintf
call. Since aFILE
is local to a single process’s address space, this setup is only possible in multi-threaded applications; it does not apply to multi-process setups where several different processes are accessing separateFILE
objects referring to the same underlying open file. Even though you’re usingfprintf
here, each process has its ownFILE
it can lock and unlock without the others seeing the changes, so writes can end up interleaved. There are several ways to prevent this from happening:
- Allocate a synchronization object (e.g. a process-shared semaphore or mutex) in shared memory and make each process obtain the lock before writing to the file (so only one process can write at a time); OR
- Use filesystem-level advisory locking, e.g.
fcntl
locks or the (non-POSIX) BSDflock
interface; OR- Instead of writing directly to the log file, write to a pipe that another process will feed into the log file. Writes to a pipe are guaranteed (by POSIX) to be atomic as long as they are smaller than
PIPE_BUF
bytes long. You cannot usefprintf
in this case (since it might perform multiple underlying write operations), but you could usesnprintf
to aPIPE_BUF
-sized buffer followed bywrite
.