How do I know when threading.Condition.wait (timeout) has timed out or has been notified?

I am developing an application with some threads, each of which starts an infinite loop with sleep times. I want to end all threads as soon as the main one is finished, here is an example:

def main():

    display_res_stop = threading.Condition()
    display_result_t = threading.Thread(target=sample_t, args=(display_res_stop, ))
    display_result_t.start()

    time.sleep(4)

    display_res_stop.acquire()
    display_res_stop.notify()
    display_res_stop.release()


def sample_t(stop_cond):
    stop_cond.acquire()

    while True:
        print 5
        c = stop_cond.wait(10)

    stop_cond.release()

if __name__ == '__main__':
    main()

      

The problem with this solution is that I don't know if the .wait condition completed because it timed out or because it was notified. In the second case, the cycle must end.

At first I did time.sleep (t) and used streaming events, but then the application had to wait for t on all threads to pass.

I'm thinking of a mixed solution using threading.Condition and Event, but I don't know if it's the nicest (condition for "sleep" and "Event" instead of True).

+3


source to share


2 answers


In the end it was very simple, I was just focusing on the wrong thing: I just needed a dream that could be stopped by an event, and that's what Event.wait (t) does. Then the problem can only be solved with events.



import threading
import time

def sample_thread(stop_ev):
    while not stop_ev.is_set():
        print 'Thread iteration'
        stop_ev.wait(0.1)

def main():
    stop_ev = threading.Event()
    sample_t = threading.Thread(target=sample_thread, args=(stop_ev, ))
    sample_t.start()

    # Other stuff here, sleep is just dummy
    time.sleep(14)

    stop_ev.set()

    print 'End reached.'

if __name__ == '__main__':
    main()

      

+2


source


An easy way to do this is to use Python 3.2 or later, or get the backport of the current one threading

to 3.1 / 2.7 / etc. from PyPI or just copy the code for this method, let's say 3.4 source .

As the docs for Condition.wait

explain:

The return value True

if the specified timeout has not elapsed, in which case it is False

.

Changed in version 3.2: Previously, the method always returned None

.




As a side note, I'm not sure what you need Condition

here at all; you are not checking the flag inside the loop or doing anything else that should be susceptible to race conditions, you are just waiting to be notified. This means that as long as you don't need a magic auto-reset it Event

should be fine. A Event.wait

has a return True

/ False

s 2.7 / 3.1 +, not 3.2 +.

+1


source







All Articles