Python 多线程之threading condition

本文介绍了Python中的多线程Condition对象,它允许线程在特定条件满足时处理数据。Condition类包含acquire、release、wait、notify和notifyAll等方法。线程通过调用wait在条件满足前挂起,而其他线程可以使用notify或notifyAll唤醒它们。示例代码展示了如何在实际场景中使用Condition进行线程同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


使用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'  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值