以前一直担心在多线程环境下,多个线程同时调用 fprintf 往同一个 fp 写东西会不会出现交错的情况,昨天微博上问了问人,有提到 fprintf_unlocked,也说到 fprintf 是线程安全的,后来又查了一下,看到这里,http://stackoverflow.com/quest… ,其中也有提到,fprintf 在多线程下是内部持有锁的
If you’re using a single
FILEobject to perform output on an open file, then wholefprintfcalls on thatFILEwill be atomic, i.e. lock is held on theFILEfor the duration of thefprintfcall. Since aFILEis 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 separateFILEobjects referring to the same underlying open file. Even though you’re usingfprintfhere, each process has its ownFILEit 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.
fcntllocks or the (non-POSIX) BSDflockinterface; 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_BUFbytes long. You cannot usefprintfin this case (since it might perform multiple underlying write operations), but you could usesnprintfto aPIPE_BUF-sized buffer followed bywrite.