In many cases, threads need to communicate with each other. A common situation is that the secondary thread executes a specific task for the main thread and constantly reports the progress of the execution during the execution process. The preceding Conditional Variable synchronization involves inter-thread communication (threading. Condition notify method ). A more common method is to use the threading. event object.
Threading. Event allows a thread to wait for notifications from other threads. It has a built-in flag, the initial value is false. The thread enters the waiting state through the wait () method until another thread calls the Set () method to set the built-in flag to true, event notifies all threads in the waiting state to resume running. You can also use the isset () method to query the current value of the built-in state of the envent object.
Example:
Import Threading
Import Random
Import Time
Class Mythread (threading. Thread ):
Def _ Init __ (Self, threadname, event ):
Threading. thread._ Init __ (Self, name = threadname)
Self. threadevent = event
Def Run (Self ):
Print " % S is ready " % Self. Name
Self. threadevent. Wait ()
Print " % S run! " % Self. Name
Sinal = threading. Event ()
For I In Range (10 ):
T = mythread (STR (I), Sinal)
T. Start ()
Sinal. Set ()