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()
由于msvcrt是标准库的一部分,我假设您已经拥有了它。msvcrt(microsoftvisualc运行时)模块只实现了msrtl中可用的少量例程,但是它实现了文件锁定。 下面是一个例子:
所示的示例具有与
fcntl.flock()
相似的函数,但是代码非常不同。只支持独占锁。 与fcntl.flock()
不同的是,没有起始参数(或从何而来)。锁定或解锁调用仅对当前文件位置起作用。这意味着,为了解锁正确的区域,我们必须将当前文件位置移回读取或写入之前的位置。解锁后,我们现在必须再次推进文件位置,回到读或写之后的位置,这样我们就可以继续了。在如果我们解锁了一个我们没有锁定的区域,那么我们不会得到错误或异常。在
相关问题 更多 >
编程相关推荐