Use Threading. The event enables threads to communicate with each other before Python: Using the Threading module to implement multithreaded programming VII [using condition to implement complex synchronization] we have initially implemented the basic functions of communication between threads, but a more general approach is to use the threading . The event object. Use Threading. Event can cause a thread to wait for notification from other threads, we pass this event to the thread object, and the event defaults to a built-in flag with the initial value false. Once the thread passes through the wait () method to the waiting state until another thread calls the event's set () method to set the built-in flag to true, the event notifies all waiting states that the thread resumes running.
Copy Code code 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'll 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 operation effect is as follows:
Copy Code code as follows:
I am thread-1,i'll sleep ...
I am thread-2,i'll sleep ...
I am thread-3,i'll sleep ...
Main thread sleep 3 seconds ...
I am Thread-1, I awake ... I am Thread-2, I awake ...
I am Thread-3, I awake ...