A class of threads needs to meet the criteria before it can continue execution.
Python provides support for threading.condition objects for conditional variable threading.
In addition to providing a method for Rlock () or lock (),
The Wait (), notify (), Notifyall () methods are also available.
Wait ([timeout]): Thread hangs until a notify notification is received or timed out (optional, floating-point number, in seconds s)
Will be awakened to continue running. Wait () must be called before the lock is obtained, or runtimeerror will be triggered.
Calling wait () releases lock until the thread is notify (), Notifyall (), or a time-out thread to regain lock.
Notify (N=1): Notifies other threads that the suspended thread will start running after receiving this notification.
The default is to notify a thread that is waiting for the condition, up to n waiting threads. The Notify () must be called before it has been acquired by Lock,
Otherwise, RuntimeError will be triggered. Notify () does not voluntarily release lock.
Notifyall (): If the wait state thread is more, the Notifyall is to notify all threads (this is generally used less)
Lock_con=threading. Condition ([Lock/rlock]): The lock is an optional option,
By default, a Rlock () is created and is generally used by default.
ImportThreading,time fromRandomImportRandintclassProducer (Threading. Thread):defRun (self):GlobalL whileTrue:val=randint (0,100) #Print (' >>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>> > ') Print('producers', Self.name,'Append'+Str (val), L)ifLock_con.acquire (): L.append (val) lock_con.notify () lock_con.release () Time.sleep (3)classConsumer (Threading. Thread):defRun (self):GlobalL whileTrue:lock_con.acquire ()ifLen (L) = =0:lock_con.wait ()Print('>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>>>>') Print('Consumer', Self.name,'Delete'+str (l[0]), L)delL[0] Lock_con.release () time.sleep (0.5)if __name__=='__main__': L=[] Lock_con=Threading. Condition () Threads=[] forIinchRange (5): Threads.append (Producer ()) Threads.append (Consumer ()) forTinchThreads:t.start () forTinchThreads:t.join ()
I'm using python3.7, and I feel that Python's cause of concurrency optimization in multiple processes is always appearing to be messy.
Which great God knows to speak.
Python Threading Conditional variable synchronization