3.2.4 Event

Events

An event is a simple synchronization object;

An event is a simple synchronization objects;

the event represents an internal flag,

Events represent an internal mark,

and threads can wait for the flag to be set, or set or clear the flag themselves.

And the thread can wait flag is set, you can set or clear the flag itself.

event = threading.Event()

event.wait()

# a client thread can wait for the flag to be set

A client thread can wait flag is set

event.set()

event.clear()

# a server thread can set or reset it

A server thread may be set or reset flag

If the flag is set, the wait method doesn’t do anything.

If the flag is set, wait () method does not do anything

If the flag is cleared, wait will block until it becomes set again.

If the flag is cleared, wait () method blocks until the flag is set again

Any number of threads may wait for the same event.

Any number of threads can wait for the same event

Enable interaction between two or more threads through the Event, the following is an example of a traffic light, i.e. starting a thread does traffic lights, vehicle generates several threads do, according to the vehicle running red

Light stop, green line rules.

Here is an example of event traffic lights

Threading Import 
Import Time 

Event = threading.Event () # writing event, event instantiate a 

def light (): # lights 
    count = 0 # Set countdown 
    event.set () # Event start 
    the while True: 
        IF. 5 <COUNT <. 11: when the red light # 6-10 sec 
            Print ( '\ 033 [. 1; 30; 41mRed Light IS Counting \ 033 [0m', COUNT) 
            The Event.CLEAR () # red light when the event ends 
        elif count> 10: # exceeded 10 seconds cycle ends, counter to zero, restarting the event 
            COUNT = 0 
            event.set () 
        the else: # 0-5 seconds green light, when the event starts 
            print ( '\ 033 [1; 30; 42mGreen light is counting \ 033 [0m ', COUNT) 
        the time.sleep (. 1) 
        COUNT =. 1 + 

DEF CAR (name): 
    the while True:
        if event.is_set (): # event start time, the green light, can pass 
            Print ( '\ 033 [. 1; 30; 42m% passing ... IS S \ 033 [0m' name%) 
            the time.sleep (. 1) 
        the else : 
            Print ( '\ 033 [. 1; 30; 41M% S IS waiting ... \ 033 [0m' name%) 
            event.wait () # event waiting, the red light 


light1 = threading.Thread (target = light, ) 
light1.start () 
CAR1 of the threading.Thread = (target = CAR, args = ( 'the BMW',)) 
car1.start ()

operation result

Event_Result

Guess you like

Origin www.cnblogs.com/infinitecodes/p/12118586.html