2012-10-02 2 views
3

저는 파이썬 - 동물원을 사용하여 잠금을 사용하고 있습니다. 파일을 볼 때 알림을 기다리는 실행 방법을 찾으려고합니다. 왜냐하면 zookeeper.exists()이 즉시 차단되기 때문입니다.알림 및 대기를위한 Python 라이브러리가 있습니까?

기본적으로 아래에 나열된 코드가 있지만 notify()wait_for_notification() 기능을 구현하는 가장 좋은 방법은 확실하지 않습니다. os.kill()signal.pause()으로 처리 할 수 ​​있지만, 나중에 한 프로그램에 여러 개의 잠금이있는 경우 문제가 발생할 가능성이 있습니다. 특정 종류의 Python 라이브러리가 있습니까? 나는 예를 확장 한

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

이 조금을 만드는 : 파이썬의 스레딩 모듈에서

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 

답변

9

조건 변수는 아마 당신이 뭘 하려는지를위한 아주 좋은 적합 귀하의 목적에 맞게 조정하는 방법을 분명히하시오.

#!/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() 
+0

환상적인, 그 트릭을 완벽하게했습니다. 정말 고마워! – paul88888