Analysis of producer and consumer operation instances using python conditional variables, and python conditional variables
This article describes the producer and consumer operations of python conditional variables. We will share this with you for your reference. The details are as follows:
Mutex lock is the simplest thread synchronization mechanism. In the face of complicated thread synchronization problems, Python also provides a Condition object. Condition is called a Condition variable. In addition to providing acquire and release methods similar to Lock, it also provides wait and policy methods. The thread first acquire a condition variable and then judges some conditions. If the condition is not met, wait will. If the condition is met, after some processing changes the condition, other threads will be notified through the notify method, and other threads in the wait status will re-judge the condition after receiving the notification. This process is constantly repeated to solve complicated synchronization problems.
It can be considered that the Condition object maintains a Lock/RLock and a waiting pool. The thread obtains the Condition object through acquire. When the wait method is called, the thread releases the internal lock of the Condition and enters the blocked State (but it does not actually block the current thread) record this thread in the waiting pool. When the notify method is called, the Condition object selects a thread from the waiting pool and notifies it to call the acquire method to try to obtain the lock.
The constructor of the Condition object can take a Lock/RLock object as the parameter. If it is not specified, the Condition object will create an RLock internally.
Typical thread synchronization problems-producer and consumer problems can be easily solved using conditional variables.
import threadingimport timeclass Producer(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global count while True: con.acquire() if count <20: count += 1 print self.name," Producer product 1,current is %d" %(count) con.notify() else: print self.name,"Producer say box is full" con.wait() con.release() time.sleep(1)class Consumer(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global count while True: con.acquire() if count>4: count -=4 print self.name,"Consumer consume 4,current is %d" %(count) con.notify() else: con.wait() print self.name," Consumer say box is empty" con.release() time.sleep(1)count = 0con = threading.Condition()def test(): for i in range(1): a = Consumer() a.start() for i in range(1): b =Producer() b.start()if __name__=='__main__': test()
The above Code assumes that the consumer consumes faster and the output result is: