Saturday, April 6, 2013

Standard I/O Locking

stdio is inherently thread-safe.  Each opened stream is associated with a lock, a lock count and an owning thread.  Thread must acquires the lock to become the owning thread before issuing any I/O call.

Still, it may need to lock the file to allow multiple I/O calls to complete in a thread.  flockfile() waits until the stream is no longer locked and then acquire the lock, increase the lock count and become the owning thread.

funlockfile() release the lock after finishing up the I/O calls.

ftrylockfile() is a non-blocking version of flockfile.

Using these calls, programmer can control the locking and can work with a set of I/O calls in standard library which does not check for locks and thus increases performance (e.g. fgetc_unlocked, fgets_unlocked, fwrite_unlocked).

No comments: