Python condition variable timeout
Asked Answered
K

2

5

I have thread1 which is waiting on a condition from thread2. But it could be that thread2 is never signalling the condition variable. So I have added a timeout to the wait call in thread 1, like this:

cv.acquire()
cv.wait(1.0)
cv.release()

How can I know if the condition variable was signaled or a timeout occurred? wait does not seem to return any value. The python documentation on Condition Objects gives no clues about this.

Karaite answered 9/7, 2012 at 8:47 Comment(0)
M
7

You are not supposed to care; the typical case is that your waiting thread checks some shared state until that state matches some condition.

The documentation example is thus:

cv.acquire()
while not an_item_is_available():
    cv.wait()
get_an_available_item()
cv.release()

and the documentation also states:

[…] threads that are interested in a particular change of state call wait() repeatedly until they see the desired state

If you do have a pressing need to distinguish between a timeout and a signal, you'll need to use Event objects instead; the .wait(timeout) call on an Event object returns None if the flag wasn't set (which only happens when the timeout was reached).

Mira answered 9/7, 2012 at 8:59 Comment(3)
Moreover, "a timeout occurred" does not preclude "desired condition achieved". For instance, suppose you wait for 0.1 second, and after exactly 0.1 second, just as the timeout expires, the event for which you were waiting also occurs. You'll wind up with race conditions if you try to use "whether a timeout occurred" as your indicator.Venusian
But I need to specially handle the case of a timeout! In case of a timeout, I will shut down my process. I do not care if right after the timeout the condition is satisfied: I will shut down the process anyway. For me the timeout is an important signal. If the condition variable does not provide this information, it is probably not a suitable method to achieve what I want.Karaite
And more: I do not want to check forever if an_item_is_available. I am waiting for it to be available within 1s. If it is not, bad luck, I will move on.Karaite
C
7

Martijn's answer was true for older versions of Python, however in 3.2, this changed. The method wait() now returns False on timeout.

Interestingly, there is now a wait_for() method as well. This takes a predicate method, and waits for it to evaluate to True. Upon timing out, it returns False.

Causeway answered 15/12, 2013 at 21:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.