python - Python2.7中带超时的锁

标签 python multithreading concurrency locking

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

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 队列具有超时功能 Queue module在 2.7 中

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

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

关于python - Python2.7中带超时的锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149889/

相关文章:

python - 有没有办法为 jupyter 笔记本中的新单元设置默认标签?

python - 在 Python 中按键对字典列表进行排序

java - 交错并行文件读取比顺序读取慢?

c# - ConcurrentBag 的正确用法是什么?

java - 覆盖 ThreadPoolExecutor 中的 execute()

python - Python Meep 中的 Vector3

python - 路易吉的任务去哪儿了?

c++ - 无法将字符串传递给 CreateThread 接收器

c# - 多个并发操作的 UI 更新

c# - 单例时间跨多个区域触发 Azure Function