There is a class of threads that need to meet the criteria before they can proceed, and Python provides support for the Threading.condition object for the conditional variable thread, which, in addition to providing a rlock () or lock () method, also provides wait (), notify (), Notifyall () method.
Lock_con=threading. Condition ([Lock/rlock]): The lock is an optional option, does not pass in the lock, and the object automatically creates a Rlock ().
- Wait (): Called when the condition is not satisfied, the thread releases the lock and enters the waiting block
- Notify (): Called after condition creation, notifies the waiting pool to activate a thread
- Notifyall (): Called after condition creation, notifies the waiting pool to activate all threads
import threading,timefrom random import Randintclass Producer (threading. Thread): def run (self): global L while True:val=randint (0,100) print (' producer ', self.na Me, ": Append" +str (val), L) if Lock_con.acquire (): L.append (val) lock_con.notify () Lock_con.release () Time.sleep (3) class Consumer (threading. Thread): def run (self): global L while True:lock_con.acquire () If Len (L) ==0: Lock_con.wait () print (' Consumer ', Self.name, ':D elete ' +str (l[0]), L) del l[0] Lock_con. Release () Time.sleep (0.25) if __name__== "__main__": l=[] lock_con=threading. Condition () #创建条件变量锁 threads=[] for I in range (5): Threads.append (Producer ()) Threads.append (Consumer ()) For T in Threads: #启动5个生产, 1 Consumer thread Objects T.start () for T in Threads:t.join ()
Python Basics-Condition variables