The condition object provided by Python provides support for complex thread synchronization issues. condition is called a conditional variable and provides the wait and notify methods in addition to the acquire and release methods similar to lock. The thread first acquire a condition variable and then determines some conditions. Wait if the condition is not met, and if the condition is met, after some processing changes the condition, the other thread is notified by the Notify method, and the other thread in the wait state will be re-judged after receiving the notification. Constantly repeating this process to solve complex synchronization problems.
You can assume that the condition object maintains a lock (Lock/rlock) and a waiting pool. The thread obtains the condition object through acquire, and when the wait method is called, the thread releases the lock inside the condition and enters the blocked state while recording the thread in the waiting pool. When the Notify method is called, the condition object picks a thread from the waiting pool and notifies it to invoke the Acquire method to fetch the lock.
The constructor of the condition object can accept a Lock/rlock object as a parameter, and if not specified, the condition object creates a rlock on its own internally.
In addition to the Notify method, the Condition object provides a Notifyall method that notifies all threads in the waiting pool to attempt to acquire an internal lock. As a result of the above mechanism, threads in the waiting state can only be awakened by the Notify method, so the role of notifyall is to prevent the thread from ever being in a state of silence.
#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImport TimeclassProducer (Threading. Thread):defRun (self):GlobalCount whileTrue:ifCon.acquire ():ifCount > 1000: con.wait ()Else: Count+ = 100msg= Self.name +'Produce, Count ='+Str (count)Printmsg con.notify () con.release () Time.sleep (1)classConsumer (Threading. Thread):defRun (self):GlobalCount whileTrue:ifCon.acquire ():ifCount < 100: con.wait ()Else: Count-= 3msg= Self.name +'Consume 3, Count ='+Str (count)Printmsg con.notify () con.release () Time.sleep (1) Count= 500Con=Threading. Condition ()defTest (): forIinchRange (2): P=Producer () P.start ( ) forIinchRange (5): C=Consumer () C.start ( )if __name__=='__main__': Test ()
Python threading Knowledge re-learning e---condition variable synchronization condition