python - 如何在 Python 中使用计时器解锁条件?

标签 python timer locking python-multithreading

我有一个锁定的条件变量,它处于等待状态。我想使用计时器从单独的线程通知它。获取锁成功,但是在调用notify时,抛出未获取锁的异常。

我在 Python 2.7 和 3.6 中尝试了不同的方法,它们的行为方式相同。

from threading import Timer, Lock, Condition

lock = Lock()
cond = Condition(lock)
timer = Timer(2, lambda: cond.notify_all())

with cond:
    timer.start()
    cond.wait()

我收到这个错误:

  File "c:\python27\Lib\threading.py", line 384, in notify
    raise RuntimeError("cannot notify on un-acquired lock")

最佳答案

如前所述here ,问题是因为获取了锁并在两个单独的线程(主线程和计时器线程)上调用了通知。

您需要获取计时器线程中的锁才能从中调用通知。请详细描述您的用例,以便我们为您提供帮助并建议实现此目标的替代方案。

关于python - 如何在 Python 中使用计时器解锁条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56803390/

相关文章:

python - 在 Python3.x 中构建具有中序和先序遍历的树

python - 如何在 IPython shell 中获取或激活虚拟环境?

android - 如何使倒数计时器在所有 Activity 中显示相同的时间

c++ - 如果我锁定变量,是否必须将复杂类型标记为 `volatile`?

c - STDIO锁定: how to check if every flockfile() has been matched by funlockfile()?

python - 如何在python中读取动态生成的文件并建立索引

python - 如何将numpy数组转换为Matlab矩阵?

java - 安卓服务停止

javascript - 番茄钟计时器变为负数并开始计数

objective-c - 与锁相比,dispatch_sync 是否具有概念上的性能优势?