擅长:python、mysql、java
<p>您基本上已经开发了二进制信号量(或互斥体)的文件系统版本。它是一个经过充分研究的用于锁定的结构,因此只要您正确地掌握了实现细节,它就应该可以工作。诀窍是让“测试并设置”操作,或者在您的例子中是“检查存在并移动”,使之成为真正的原子。为此,我会用这样的方法:</p>
<pre><code>lock_acquired = False
while not lock_acquired:
try:
move(fh, fhtemp)
except:
sleep(3)
else:
lock_acquired = True
# do your writing
move(fhtemp, fh)
lock_acquired = False
</code></pre>
<p>这个程序在大部分时间内都可以正常工作,但是正如前面提到的,如果另一个进程在检查文件是否存在和调用<code>move</code>之间移动文件,则可能会出现问题。我想您可以解决这个问题,但我个人建议您坚持使用经过良好测试的互斥体算法。(我已经翻译/移植了Andrew Tanenbaum的<em>现代操作系统</em>中的上述代码示例,但有可能我在转换过程中引入了错误-只是警告一下)</p>
<p>顺便说一下,Linux上<code>open</code>函数的手册页提供了以下文件锁定解决方案:</p>
<blockquote>
<p>The solution for performing atomic file locking using a lockfile is to create a unique file on the same file system (e.g., incorporating hostname and pid), use link(2) to make a link to the lockfile. If link() returns 0, the lock is successful. Otherwise, use stat(2) on the unique file to check if its link count has increased to 2, in which case the lock is also successful.</p>
</blockquote>
<p>要在Python中实现这一点,可以执行以下操作:</p>
^{2}$