2013-05-24 2 views
5

나는이 같은 파이썬 3 시퀀스를 사용하고 시간 초과 효과를 얻는 방법을 알지 못합니다.파이썬 잠금 문 및 시간 제한

당신은 컨텍스트 매니저로 아주 쉽게 수행 할 수 있습니다
+0

그렇게 할 수없는 것처럼 보입니다. – Blender

+0

[this] (http://stackoverflow.com/questions/8392640/how-to-implement-a-lock-with-a-timeout-in-python-2-7) 도움이 될 수도 있습니다. – shx2

+0

내가 원하는 ;-). – Tsf

답변

5

:

import threading 
from contextlib import contextmanager 

@contextmanager 
def acquire_timeout(lock, timeout): 
    result = lock.acquire(timeout=timeout) 
    yield result 
    if result: 
     lock.release() 


# Usage: 
lock = threading.Lock() 

with acquire_timeout(lock, 2) as acquired: 
    if acquired: 
     print('got the lock') 
     # do something .... 
    else: 
     print('timeout: lock not available') 
     # do something else ... 

* 참고 : Lock.acquire

1
timeout 인수가 아니기 때문에이 파이썬 2.x에서 작동하지 않습니다

약간 더 좋은 버전 :

import threading 
from contextlib import contextmanager 


class TimeoutLock(object): 
    def __init__(self): 
     self._lock = threading.Lock() 

    def acquire(self, blocking=True, timeout=-1): 
     return self._lock.acquire(blocking, timeout) 

    @contextmanager 
    def acquire_timeout(self, timeout): 
     result = self._lock.acquire(timeout=timeout) 
     yield result 
     if result: 
      self._lock.release() 

    def release(self): 
     self._lock.release() 

# Usage: 
lock = TimeoutLock() 

with lock.acquire_timeout(3) as result: 
    if result: 
     print('got the lock') 
     # do something .... 
    else: 
     print('timeout: lock not available') 
     # do something else ... 

그래서, 당신이 threading.Lock를 서브 클래스 수 없습니다 나타납니다 대신 래퍼 클래스를 만들어야했습니다.

+0

니스! 나는 시도 할 것이다. Thnx. – Tsf