The condition object can be used to process data after certain events have been triggered or to meet certain conditions, condition in addition to the acquire method and release method with the lock object, there are wait methods, notify methods, The Notifyall method is used for conditional processing.
Threading. Condition ([lock]): Creates a condition that supports referencing a lock object from outside (for situations where multiple condtion share a lock), by default creating a new lock object.
Acquire ()/release (): Get/Release Lock
Wait ([timeout]): The thread hangs until it receives a notify notification or timeout (optional, floating-point number, in seconds s) before it wakes up and continues to run. 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, by default notifying a thread that is waiting for the condition, up to n waiting threads. Notify () must be called before the lock is obtained, or 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)
Example:
Import threading Import Time l=[] class boy (threading. Thread): def __init__ (self,cond,name = ' A boy '): Threading. Thread.__init__ (self) self.cond = cond Self.name = name def run (self): Time.sleep (1) ' Boy start conversation, make sure the girl thread stared before send notify ' Self.cond. Acquire () Print Self.name + ': Hello pretty~,i Miss You\n ' Self.cond.notify () self.cond.wait ( ) Print Self.name + ': Like moth missing fire\n ' self.cond.notify () self.cond.wait () Print Self.name + ': And I bought a gift for the list l\n ' L.append (' Channel5 ') Self.cond.noti FY () self.cond.release () Class Girl (threading. Thread): def __init__ (self,cond,name = ' A girl '): Threading. Thread.__init__ (self) self.cond = cond Self.name = name Def run (Self): Self.cond.acquire () self.cond.wait () Print Self.name + ': Really, show me how Mu Ch~\n ' Self.cond.notify () self.cond.wait () Print Self.name + ': you\ ' re so sweet~ ' s Elf.cond.notify () self.cond.wait () Print Self.name + ': wow~~, that\ ' s ' +l.pop () + '---the one I dreamed F Or so long, I love You ' Self.cond.release () if __name__ = = ' __main__ ': Cond = Threading. Condition () husband = Boy (cond, ' Aidan ') wife = Girl (cond, ' PPP ') Husband.start () Wife.start () #husband. Start () husband.join () #wait untill these, threads end Wife.join () print ' End converdarion\ N
Python Multi-thread threading condition