boost::interprocess 中 win32 文件锁定的模拟是什么?
我应该使用什么同步机制来提供对 boost 中文本文件的独占访问? 该文件可能仅由一个进程的线程访问。
What sync mechanism should I use to give exclusive access to the text file in boost?
The file will likely be accessed by threads from only one process.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
文件锁定 API 通常用于进程间锁定。 如果您在单个进程中,则 Boost.Thread 包 中的所有内容适合您需求的就可以了。 外部进程应该使用Boost.Interprocess。 您可能想阅读来自 Boost.Interprocess 的以下警告:
如果您计划像命名互斥体一样使用文件锁,请小心,因为可移植文件锁具有同步限制,主要是因为不同的实现(POSIX、Windows)提供不同的保证。 进程间文件锁具有以下限制:
file_lock
是否同步同一进程中的两个线程。file_lock
对象。第一个限制主要来自 POSIX,因为文件句柄是每进程属性而不是每线程属性。 这意味着如果一个线程使用
file_lock
对象锁定文件,其他线程将看到该文件已锁定。 另一方面,Windows 文件锁定机制提供线程同步保证,因此尝试锁定已锁定文件的线程将被阻塞。第二个限制来自于文件锁定同步状态与 Windows 中的单个文件描述符相关联的事实。 这意味着如果创建两个指向同一文件的 file_lock 对象,则无法保证同步。 在 POSIX 中,当使用两个文件描述符来锁定文件时,如果关闭一个描述符,则调用进程设置的所有文件锁都会被清除。
总而言之,如果您计划在进程中使用文件锁定,请使用以下限制:
file_lock
对象。The file locking APIs are generally for inter process locking. If you are in a single process everything in Boost.Thread package that suits your needs will do. Outside processes the Boost.Interprocess should be used. You might want to read the following warning from Boost.Interprocess:
If you plan to use file locks just like named mutexes, be careful, because portable file locks have synchronization limitations, mainly because different implementations (POSIX, Windows) offer different guarantees. Interprocess file locks have the following limitations:
file_lock
synchronizes two threads from the same process.file_lock
objects pointing to the same file.The first limitation comes mainly from POSIX, since a file handle is a per-process attribute and not a per-thread attribute. This means that if a thread uses a
file_lock
object to lock a file, other threads will see the file as locked. Windows file locking mechanism, on the other hand, offer thread-synchronization guarantees so a thread trying to lock the already locked file, would block.The second limitation comes from the fact that file locking synchronization state is tied with a single file descriptor in Windows. This means that if two file_lock objects are created pointing to the same file, no synchronization is guaranteed. In POSIX, when two file descriptors are used to lock a file if a descriptor is closed, all file locks set by the calling process are cleared.
To sum up, if you plan to use file locking in your processes, use the following restrictions:
file_lock
object per process.我想它是 acquire_file_lock
它是一致的使用锁的非Boost实现。
I suppose it is acquire_file_lock
It is consistent with a non-boost implementation of a lock.
如果您确定只能从一个进程访问它,则在线程本地存储中使用带有文件句柄的读写锁可能是一种解决方案。 这将模拟上述情况,只有一名作者和多名读者。
If you are sure it will only be accessed from one process, a read-write lock with file handles in thread local storage could be a solution. That would simulate the above with only one writer but several readers.