使用Condition对象可以在某些事件触发或者达到特定的条件后才处理数据,Condition除了具有Lock对象的acquire方法和release方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。
threading.Condition([lock]):创建一个condition,支持从外界引用一个Lock对象(适用于多个condtion共用一个Lock的情况),默认是创建一个新的Lock对象。
acquire()/release():获得/释放 Lock
wait([timeout]):线程挂起,直到收到一个notify通知或者超时(可选的,浮点数,单位是秒s)才会被唤醒继续运行。wait()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。调用wait()会释放Lock,直至该线程被Notify()、NotifyAll()或者超时线程又重新获得Lock.
notify(n=1):通知其他线程,那些挂起的线程接到这个通知之后会开始运行,默认是通知一个正等待该condition的线程,最多则唤醒n个等待的线程。notify()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。notify()不会主动释放Lock。
notifyAll(): 如果wait状态线程比较多,notifyAll的作用就是通知所有线程(这个一般用得少)
举例:
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 you in the list L\n' L.append('channel5') self.cond.notify() 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 much~\n' self.cond.notify() self.cond.wait() print self.name +':you\'re so sweet~' self.cond.notify() self.cond.wait() print self.name +':wow~~, that\'s '+L.pop()+'---the one I dreamed for 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 two threads end wife.join() print 'end converdarion\n'
Python 多线程之threading condition
原文地址:http://blog.csdn.net/suipingsp/article/details/40303429