Ned Ruggeri
Ned Ruggeri

Reputation: 1108

When does file stream locking occur in glibc?

Reading the glibc documentation, I recently learned that calls to getc may have to wait to acquire a lock to read a file. I wanted to verify that when using buffering a lock is only acquired when the actual file needs to be read to replenish the buffer.

Thanks!

Upvotes: 2

Views: 432

Answers (1)

David Gelhar
David Gelhar

Reputation: 27900

The lock invoked by getc provides application-level locking of the stdio FILE object, to allow thread-safe access to the same FILE object by multiple threads in the same application. As such, it will need to be acquired every time a character is read, not just when the buffer is replenished.

But, if you aren't accessing the FILE from multiple threads, you'll never have to wait for the lock. If the overhead of acquiring/releasing the lock is too much (measure this; don't just assume), you also have the option of manually locking/unlocking using flockfile and funlockfile, then using getc_unlocked.

Upvotes: 3

Related Questions