glibc什么时候会发生文件流锁定?
通过阅读 glibc 文档,我最近了解到调用 getc 可能必须等待获取锁才能读取文件。我想验证在使用缓冲时,仅当需要读取实际文件以补充缓冲区时才获取锁。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
getc 调用的锁提供 stdio FILE 对象的应用程序级锁定,以允许同一应用程序中的多个线程对同一 FILE 对象进行线程安全访问。因此,每次读取字符时都需要获取它,而不仅仅是在填充缓冲区时获取。
但是,如果您不从多个线程访问 FILE,则永远不必等待锁定。如果获取/释放锁的开销太大(衡量这一点;不要只是假设),您还可以选择使用
flockfile
和funlockfile
手动锁定/解锁>,然后使用getc_unlocked
。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
andfunlockfile
, then usinggetc_unlocked
.