我使用python-zookeeper进行锁定,并且尝试找出一种方法,使执行在监视文件时等待通知,因为zookeeper.exists()
会立即返回,而不是阻塞。
基本上,我有下面列出的代码,但我不确定实现notify()
和wait_for_notification()
函数的最佳方式。可以用os.kill()
和signal.pause()
来实现,但我确信如果我以后在一个程序中有多个锁,这可能会导致问题--有没有一个特定的Python库适合这类事情?
def get_lock(zh):
lockfile = zookeeper.create(zh,lockdir + '/guid-lock-','lock', [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL | zookeeper.SEQUENCE)
while(True):
# this won't work for more than one waiting process, fix later
children = zookeeper.get_children(zh, lockdir)
if len(children) == 1 and children[0] == basename(lockfile):
return lockfile
# yeah, there's a problem here, I'll fix it later
for child in children:
if child < basename(lockfile):
break
# exists will call notify when the watched file changes
if zookeeper.exists(zh, lockdir + '/' + child, notify):
# Process should wait here until notify() wakes it
wait_for_notification()
def drop_lock(zh,lockfile):
zookeeper.delete(zh,lockfile)
def notify(zh, unknown1, unknown2, lockfile):
pass
def wait_for_notification():
pass
2条答案
按热度按时间oaxa6hgo1#
Python线程化模块中的Condition变量可能非常适合您要做的事情:
http://docs.python.org/library/threading.html#condition-objects
我扩展了这个例子,使它更明显地说明如何根据您的目的来修改它:
xyhw6mcr2#
我的回答可能与您的问题无关,但与问题标题有关。
更多信息,请访问:https://docs.python.org/3/library/threading.html#event-objects