Search code examples
pythontimerlockingpython-multithreading

How to unblock a Condition using a Timer in Python?


I have a locked conditional variable, which is in waiting state. I want to notify it from a separate thread using a Timer. The Lock is acquired successfully, however when calling notify, it raises an exception about the lock being not acquired.

I've tried different approaches in Python 2.7 and 3.6, and it behaves the same way.

from threading import Timer, Lock, Condition

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

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

I am getting this error:

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

Solution

  • As mentioned here, the issue is because the lock is acquired and notify is called on two separate threads(main thread and timer thread).

    You need to acquire the lock in the timer thread to be able to call notify from it. Please describe your use-case in detail for us to help you and suggest an alternative to achieve this.