Python 多线程之threading condition
来源:互联网 发布:2016网络博客娱乐网站 编辑:程序博客网 时间:2024/04/28 10:38
使用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'
3 0
- Python 多线程之threading condition
- python多线程threading.Condition示例及解析
- python --- 多线程之threading
- Python多线程之threading Event
- Python多线程之:threading模块
- python爬虫(threading.Condition())
- python学习之5 多线程threading
- Python多线程--(2)之threading模块
- Python多线程编程之thread和threading
- Python:使用threading模块实现多线程编程七[使用Condition实现复杂同步]
- Python:使用threading模块实现多线程编程七[使用Condition实现复杂同步]
- python使用threading.condition实现生产者消费者
- python threading/lock&Rlock&condition 锁
- python—threading.Condition【threading模块介绍05】
- Python 多线程 Threading模块
- Python threading多线程编程
- Python多线程1:threading
- python 多线程threading
- java中接口有什么作用?
- lucene入门 ==》 实例
- mysql数据库 实现类似标记序号的伪列
- mysql 远程 ip访问
- 菜鸟版JAVA设计模式-从抽象与实现说桥接模式
- Python 多线程之threading condition
- Android OpenGL ES 简明开发教程二:构造OpenGL ES View
- ndk-build的用法
- jquery 实现Ajax--[转]JQuery.Ajax之错误调试帮助信息
- Linux下安装JDK-(rpm版)
- c标签 判断 对象是否为空
- UVA - 1352
- HEVC参考程序--编码器性能分析
- ORA-01502: 索引 'xx' 或这类索引的分区处于不可用状态