Thread synchronization in addition to using thread locks , You can also use event signals Event class . Why use event signals ? In fact, we can understand the truth from life , Like two people cooking together . Wash the pot alone , Wash rice alone . If the person who washes the rice first works faster , Or rather lazy , Just wash rice once , The washed rice is immediately poured into the pan , And the other one hasn't cleaned the pot yet , What will happen then ? It's not to scold the pot washer , It's just a fight . Because clean rice , Put it in a dirty pot , So the final result is still not clean , It's like doing work for nothing . So in life , When the two work together , I'll let someone wash the rice first , Until the person who washes the pot cleans it , That would not have happened . In multithreading , It's often the same thing . For example, there is a printer in the computer , I printed a copy first A file , It's not finished printing , Let's print another one B file , Will the printer print first B Documents , If you look at it carefully , It won't . Why can we do this ? In fact, this is the result of event signal synchronization . Because the printer knows A The document has not been printed , So the event signal doesn't notify B The document begins to print .
Now let's simulate the printing process and write an example , Use it here Event Class to synchronize the above relationship . adopt threading.Event() You can create an event management flag , This sign (event) The default is False,event There are four main methods to call an object :
event.wait(timeout=None): The thread calling the method will be blocked , If set timeout Parameters , After a timeout , The thread stops blocking and continues execution ;