Event=event ()
Event.isset () # Returns the status value of event to True False
Event.wait () #等待其他线程发出event. Set () To continue execution event.isset () = False to block threads
Event.wait (3) #如果超过3秒, even if not received event.set () will continue to execute
Event.set () # Sets the status value of event to true, all blocking pool threads are activated into a ready state, waiting for the operating system to dispatch
Event.clear () # Recovery event has a status value of False
Simulate multiple client connection servers to detect if the server is functioning properly? The server must be up before the client can connect.
fromThreadingImportEvent fromThreadingImportThread fromThreadingImportCurrent_threadImporttimeevent=Event ()defConn ():Print('is connecting ...') n=0 while notEvent.is_set ():ifn = = 5: Print('%s Try too many count!'%Current_thread (). GetName ())returnevent.wait (1) Print('%s Try%s'%(Current_thread (). GetName (), n)) n+ = 1Print('Connected')defcheck ():Print('server is starting ...') Time.sleep (5) Print('Server is started!') Event.set ()if __name__=='__main__': Conn1= Thread (target=conn) Conn2= Thread (target=conn) Conn3= Thread (target=conn) Check1= Thread (target=check) Conn1.start () Conn2.start () Conn3.start () Check1.start ()
Run Result: can set the server start time, and the connection time and retry the test number, observe different results
isConnecting ... isConnecting ... isconnecting ... server isstarting ... Thread-1Try0Thread-3Try0Thread-2Try0Thread-1Try1Thread-3Try1Thread-2Try1Thread-3Try2Thread-2Try2Thread-1Try2Thread-3Try3Thread-1Try3Thread-2Try3Server isstarted! Thread-2Try4Connectedthread-1Try4Connectedthread-3Try4Connected
View Code
5.1.19 Event Events--Interaction between threads