#_*_coding:utf-8_*_#Author:leo#Date:#Email:[email protected]ImportQueue, ThreadingclassWorker (Threading. Thread):def __init__(self): threading. Thread.__init__(self) self.lock=Threading. Lock () Self.con1=Threading. Condition (self.lock) Self.con2=Threading. Condition (self.lock) self.event= Threading. Event ()#Similar results can be achieved, but not flexible enough to use the scene is not rich, this class is also thread-safeSelf.queque =queue. Queue ()Print(Self.event.is_set ())defRun (self): threading. Thread (Target=Self.customer). Start () threading. Thread (Target=self.producter). Start ()defProducter (self): with Self.con1: forAinchRange (100): Print('Productor put:', str (a)) Self.queque.put (a) self.con2.notify () self.con1.wait ()#the use of wait must ensure that it is currently secure and must be locked Print('Recevie Sigal from Con1 producting ...') Self.con2.notify_all ()defcustomer: With Self.con2: whileTrue:self.con2.wait ()Print('Recevie signal from Con2 customer ....') ifself.queque.empty (): Breakresult=Self.queque.get ()ifResult is notNone:Print('Customer Get:', str (result)) self.con1.notify () T=Worker () T.start () T.join ( )
Python Thread condition variable lock