写在前面的话
看了网上一些大牛相关博客,不是很理解,内核对象啊什么的。这篇博客用白话记录自己的学习过程以及一些理解。
event精粹
概述
事件(event)用于线程间同步和通信。比如线程A要完成某一任务(event)线程B才能执行后面的代码,怎么实现呢,就是用event。
event常用方法 | 释义 |
---|---|
set() | 开始一个事件 |
wait() | 如果未设置set状态会一直等待,否则过 |
clear() | 清除set状态 |
isSet() | 是否设置set状态 |
注意:
wait方法是阻塞的
设置完set后要使用clear方法,否则wait为真,不会等待
上代码
#!/usr/bin python
#coding=utf-8
import threading
import time
def producer():
print u'等人来买包子....'
event.wait()
#event.clear()
print event.isSet()
print u'chef:sb is coming for baozi...'
print u'chef:making a baozi for sb...'
time.sleep(5)
print u'chef:你的包子好了...'
event.set()
def consumer():
print u'chenchao:去买包子....'
event.set()
time.sleep(2)
print 'chenchao:waiting for baozi to be ready...'
print event.wait()
print u'chenchao:哎呀真好吃....'
event = threading.Event()
p = threading.Thread(target=producer,args=())
c = threading.Thread(target=consumer,args=())
p.start()
c.start()
clear()注释掉的结果
等人来买包子....
chenchao:去买包子....
True
chef:sb is coming for baozi...
chef:making a baozi for sb...
chenchao:waiting for baozi to be ready...
True
chenchao:哎呀真好吃....
chef:你的包子好了...
最后两行显然有问题,包子还没好就可以print了,要使用clear
方法清除设置的set状态。
#!/usr/bin python
#coding=utf-8
import threading
import time
def producer():
print u'等人来买包子....'
event.wait()
event.clear()
print event.isSet()
print u'chef:sb is coming for baozi...'
print u'chef:making a baozi for sb...'
time.sleep(5)
print u'chef:你的包子好了...'
event.set()
def consumer():
print u'chenchao:去买包子....'
event.set()
time.sleep(2)
print 'chenchao:waiting for baozi to be ready...'
print event.wait()
print u'chenchao:哎呀真好吃....'
event = threading.Event()
p = threading.Thread(target=producer,args=())
c = threading.Thread(target=consumer,args=())
p.start()
c.start()
结果是这样的
等人来买包子....
chenchao:去买包子....
False
chef:sb is coming for baozi...
chef:making a baozi for sb...
chenchao:waiting for baozi to be ready...
chef:你的包子好了...
True
chenchao:哎呀真好吃....
模拟异步模型中的select
#!/usr/bin python
#coding=utf-8
import threading
import time
def producer():
print u'等人来买包子....'
event.wait()
event.clear()
print event.isSet()
print u'chef:sb is coming for baozi...'
print u'chef:making a baozi for sb...'
time.sleep(5)
print u'chef:你的包子好了...'
event.set()
def consumer():
print u'chenchao:去买包子....'
event.set()
time.sleep(2)
print 'chenchao:waiting for baozi to be ready...'
while True:
if event.isSet():
print u'真好吃...'
break
else:
print u'好慢啊...'
time.sleep(1)#相当于去做自己的事去了
event = threading.Event()
p = threading.Thread(target=producer,args=())
c = threading.Thread(target=consumer,args=())
p.start()
c.start()
结果
等人来买包子....
chenchao:去买包子....
False
chef:sb is coming for baozi...
chef:making a baozi for sb...
chenchao:waiting for baozi to be ready...
好慢啊...
好慢啊...
好慢啊...
好慢啊...chef:你的包子好了...
真好吃...