event主要用在线程的通讯中,一个线程没有得到想要的资源,用event.wait()阻塞。当另一个线程给了相应的资源就用event通知所有的线程(用同一个event)
其他的线程在得到之后就可以运行了。
#event.py
import threading
class mythread(threading.Thread):
def __init__(self,threadname):
threading.Thread.__init__(self,name=threadname)
def run(self):
global event
if event.isSet():
print "I am in if"
event.clear()
event.wait()
print self.getName()
else:
print "I am in else"
print self.getName()
event.set()
event=threading.Event()
event.set()
t1=[]
for i in range(10):
t=mythread(str(i))
t1.append(t)
for i in t1:
i.start()
pc$ python event.py
I am in else
1
0
I am in if
I am in else
3
2
I am in if
I am in else
5
4
I am in if
I am in else
I am in else
8
6
7
I am in if
这个程序有时候会阻塞住,