我正在寻找python替代Java的tryAcquire信号量函数。我发现这个函数是在python版本3及更高版本中添加的。我使用的是python版本2.6.5。我有别的选择吗?我这里只有semaphore.acquire(blocking=False),这是我用Java编写的代码-(信号量释放是在另一个线程中完成的,我没有包含它的代码)
if(Sem.tryAcquire(30, TimeUnit.SECONDS))
log.info("testCall Semaphore acquired ");
else
log.error("Semaphore Timeout occured");发布于 2013-06-17 17:07:26
Semaphore是用纯Python语言实现的--参见http://hg.python.org/cpython/file/3.3/Lib/threading.py,从第236行开始。acquire方法是这样实现的:
def acquire(self, blocking=True, timeout=None):
if not blocking and timeout is not None:
raise ValueError("can't specify timeout for non-blocking acquire")
rc = False
endtime = None
with self._cond:
while self._value == 0:
if not blocking:
break
if timeout is not None:
if endtime is None:
endtime = _time() + timeout
else:
timeout = endtime - _time()
if timeout <= 0:
break
self._cond.wait(timeout)
else:
self._value = self._value - 1
rc = True
return rc你可以直接在你的代码中使用Semaphore的技术,而不是使用类,但将整个类复制到你自己的代码中可能会更容易。如果向前兼容性是一个问题,你甚至可以这样调节它:
from threading import *
from sys import version_info
if version_info < (3, 2):
# Need timeout in Semaphore.acquire,
# from Python 3.3 threading.py
class Semaphore:
...除非超过给定的超时时间,否则返回值为
True,在这种情况下返回值为False。
版本3.2中的更改:以前,该方法始终返回None。
Semaphore超时代码依赖于此行为。兔子洞似乎不会比这更深,但是,你最简单的解决方案甚至可能是复制整个3.3 threading.py,在2.x上运行所需的任何更改,并在顶部添加一个突出的注释,即您故意跟踪stdlib。
https://stackoverflow.com/questions/17143516
复制相似问题