由于msvcrt是标准库的一部分,我假设您已经拥有它。msvcrt(MicroSoft Visual C 运行时)模块仅实现 MS RTL 中可用的少量例程,但它确实实现了文件锁定。这是一个例子:
import msvcrt, os, sys
REC_LIM = 20
pFilename = "rlock.dat"
fh = open(pFilename, "w")
for i in range(REC_LIM):
# Here, construct data into "line"
start_pos = fh.tell() # Get the current start position
# Get the lock - possible blocking call
msvcrt.locking(fh.fileno(), msvcrt.LK_RLCK, len(line)+1)
fh.write(line) # Advance the current position
end_pos = fh.tell() # Save the end position
# Reset the current position before releasing the lock
fh.seek(start_pos)
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, len(line)+1)
fh.seek(end_pos) # Go back to the end of the written record
fh.close()
Run Code Online (Sandbox Code Playgroud)
显示的示例具有与 for 类似的功能fcntl.flock(),但代码非常不同。仅支持独占锁。fcntl.flock()与没有开始参数(或从哪里开始)不同。锁定或解锁调用仅对当前文件位置进行操作。这意味着为了解锁正确的区域,我们必须将当前文件位置移回到进行读取或写入之前的位置。解锁后,我们现在必须再次前进文件位置,回到读取或写入后的位置,以便我们可以继续。
如果我们解锁一个没有锁的区域,那么我们不会收到错误或异常。
| 归档时间: |
|
| 查看次数: |
3931 次 |
| 最近记录: |