与flock()函数有关的问题
我有一个关于flock()
如何工作的问题,特别是在Python中。我有一个打开串行连接的模块(通过 os.open() )。我需要确保这个线程的安全。使用 threading.Lock()
在同一个模块中工作时,很容易使其线程安全,但如果模块从不同的位置导入,它就会崩溃。
我正在考虑使用flock()
,但我很难找到足够的关于flock到底如何工作的信息。我读到,一旦文件关闭,flock()就会解锁文件。但是,如果 python 崩溃,是否存在使文件保持打开状态的情况?
如果设置了 LOCK_EX,究竟允许什么使用锁定的文件?只是锁定文件的模块?从最初运行的脚本导入的任何模块?
I have a question about how flock()
works, particularly in python. I have a module that opens a serial connection (via os.open()
). I need to make this thread safe. It's easy enough making it thread safe when working in the same module using threading.Lock()
, but if the module gets imported from different places, it breaks.
I was thinking of using flock()
, but I'm having trouble finding enough information about how exactly flock works. I read that flock() unlocks the file once the file is closed. But is there a situation that will keep the file open if python crashes?
And what exactly is allowed to use the locked file if LOCK_EX
is set? Just the module that locked the file? Any module that was imported from the script that was originally run?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当进程终止时,操作系统应该清理所有打开的文件资源(我确信有一些警告)。这是因为关闭文件时会释放咨询锁,该操作是
python
进程退出时操作系统清理的一部分。请记住, flock(2) 只是建议性的:
flock(2) 实现了读写器锁。您无法使用
LOCK_EX
对同一个文件进行两次集群,但任意数量的人都可以同时使用LOCK_SH
对同一文件进行集群(只要没有其他人拥有LOCK_EX< /code> 就可以了)。
集群工作在操作系统/进程级别,并且独立于Python模块。一个模块可能请求 n 个锁,或者跨 m 个模块请求 n 个锁。但是,在给定时间只有一个进程可以持有给定文件的
LOCK_EX
锁。“非 UNIX”系统或非本地文件系统上的 YMMV。
When a process dies the OS should clean up any open file resources (with some caveats, I'm sure). This is because the advisory lock is released when the file is closed, an operation which occurs as part of the OS cleanup when the
python
process exits.Remember, flock(2) is merely advisory:
flock(2) implements a readers-writer lock. You can't flock the same file twice with
LOCK_EX
, but any number of people can flock it withLOCK_SH
simultaneously (as long as nobody else has aLOCK_EX
on it).flock works at the OS/process level and is independent of python modules. One module may request n locks, or n locks could be requested across m modules. However, only one process can hold a
LOCK_EX
lock on a given file at a given time.YMMV on a "non-UNIX" system or a non-local filesystem.