擅长:python、mysql、java
<p>哎哟,我的错!
我应该先读一下python<a href="http://docs.python.org/2/library/threading.html#threading.Lock.acquire" rel="nofollow">reference for Locks</a>!在</p>
<blockquote>
<p>Lock.acquire([blocking])</p>
<p>When invoked with the <em>blocking</em> argument set to <code>False</code>, do not block.
If a call with <em>blocking</em> set to <code>True</code> would block, return <code>False</code>
immediately; otherwise, set the lock to locked and return <code>True</code>.</p>
</blockquote>
<p>所以我可以做一些类似的事情(或者更高级的事情:p):</p>
<pre><code>import threading
import time
def my_trylock(lock, timeout):
count = 0
success = False
while count < timeout and not success:
success = lock.acquire(False)
if success:
break
count = count + 1
time.sleep(1) # should be a better way to do this
return success
lock = threading.Lock()
my_trylock(lock, 13)
</code></pre>