This article mainly introduces Python multi-thread programming (8): Use Event to implement inter-thread communication. if you need it, refer to threading. event can implement inter-thread communication. The previous Python: Use the threading module to implement multi-thread programming. 7. [use Condition to implement complex synchronization] we have initially implemented the basic functions of inter-thread communication, however, a more general approach is to use threading. event object. With threading. Event, a thread can wait for notifications from other threads. we pass this Event to the thread object. by default, the Event has a built-in flag with the initial value of False. Once the thread enters the waiting state through the wait () method, until another thread calls the set () method of the Event to set the built-in flag to True, this Event will notify all threads in the waiting state to resume running.
The code is as follows:
'''
Created on 2012-9-9
@ Author: walfred
@ Module: thread. TreadTest8
'''
Import threading
Import time
Class MyThread (threading. Thread ):
Def _ init _ (self, signal ):
Threading. Thread. _ init _ (self)
Self. singal = signal
Def run (self ):
Print "I am % s, I will sleep..." % self. name
Self. singal. wait ()
Print "I am % s, I awake..." % self. name
If _ name _ = "_ main __":
Singal = threading. Event ()
For t in range (0, 3 ):
Thread = MyThread (singal)
Thread. start ()
Print "main thread sleep 3 seconds ..."
Time. sleep (3)
Singal. set ()
The running effect is as follows:
The code is as follows:
I am Thread-1, I will sleep...
I am Thread-2, I will sleep...
I am Thread-3, I will sleep...
Main thread sleep 3 seconds...
I am Thread-1, I awake... I am Thread-2, I awake...
I am Thread-3, I awake...