【问题标题】:Lock with timeout in Python2.7Python2.7中的超时锁定
【发布时间】:2016-02-02 09:47:02
【问题描述】:

这里接受的解决方案并不适用于所有情况,

How to implement a Lock with a timeout in Python 2.7

(特别是当没有人持有条件变量时,拥有锁的最后一个线程调用 cond.notify())

然后,我尝试了这样的自旋锁:

import threading
import time

class TimeLock(object):

    def __init__(self):
        self._lock = threading.Lock()


    def acquire_lock(self, timeout = 0):
        ''' If timeout = 0, do a blocking lock
            else, return False at [timeout] seconds
        '''
        if timeout == 0:
            return self._lock.acquire()   # Block for the lock

        current_time = start_time = time.time()
        while current_time < start_time + timeout:
            if self._lock.acquire(False): # Contend for the lock, without blocking
                return True
            else:
                time.sleep(1)
                current_time = time.time()

        # Time out
        return False

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

但是在尝试之后,自旋锁几乎总是会因阻塞锁而饿死。 还有其他解决方案吗?

【问题讨论】:

    标签: python multithreading concurrency locking


    【解决方案1】:

    原来python队列在他们的 Queue module 2.7

    我可以通过这样做来模拟超时锁定

    lock.acquire() -> Queue.get(block=True, timeout=timeout)
    lock.release() -> Queue.put(1, block=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2016-12-16
      • 2011-01-07
      • 1970-01-01
      • 2014-11-26
      • 2018-03-06
      相关资源
      最近更新 更多