gpt4 book ai didi

python - 有通知和等待的python库吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:01 25 4
gpt4 key购买 nike

我正在使用 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

最佳答案

Python 线程模块中的条件变量可能非常适合您要执行的操作:

http://docs.python.org/library/threading.html#condition-objects

我扩展了这个例子,让你更清楚地了解如何根据你的目的调整它:

#!/usr/bin/env python

from collections import deque
from threading import Thread,Condition

QUEUE = deque()

def an_item_is_available():
return bool(QUEUE)

def get_an_available_item():
return QUEUE.popleft()

def make_an_item_available(item):
QUEUE.append(item)

def consume(cv):
cv.acquire()
while not an_item_is_available():
cv.wait()
print 'We got an available item', get_an_available_item()
cv.release()

def produce(cv):
cv.acquire()
make_an_item_available('an item to be processed')
cv.notify()
cv.release()

def main():
cv = Condition()
Thread(target=consume, args=(cv,)).start()
Thread(target=produce, args=(cv,)).start()

if __name__ == '__main__':
main()

关于python - 有通知和等待的python库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12686283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com