我编写了一个与 gevent.event.Event 一起玩的脚本,但我发现 wait 方法似乎没有生效。我使用的gevent版本是1.0。
我的脚本如下,你也可以得到它here:
#!/urs/bin/env python2.7
#coding: utf-8
"""Test the usage of 'gevent.event.Event' class.
"""
import random
import gevent
from gevent.event import Event
class TestEvent(object):
def __init__(self):
self.event = Event()
def run(self):
producers = [gevent.spawn(self._producer, i) for i in xrange(3)]
consumers = [gevent.spawn(self._consumer, i) for i in xrange(3)]
tasks = []
tasks.extend(producers)
tasks.extend(consumers)
gevent.joinall(tasks)
def _producer(self, pid):
print("I'm producer %d and now I don't want consume to do something" % (pid,))
self.event.clear()
sleeptime = random.randint(0, 5) * 0.01
print("Sleeping time is %f" % (sleeptime, ))
gevent.sleep(sleeptime)
print("I'm producer %d and now consumer could do something." % (pid,))
self.event.set()
def _consumer(self, pid):
print("I'm consumer %d and now I'm waiting for producer" % (pid,))
flag = self.event.wait()
print("I'm consumer %d. Flag is %r and now I can do something" % (pid, flag))
self.event.clear()
if __name__ == '__main__':
test = TestEvent()
test.run()
脚本的输出是:
答案 0 :(得分:0)
您的制作人执行以下操作:
P-A:清除事件
P-B:设置事件
您的消费者会执行以下操作:
C-A:等待事件设置为
C-B:设置事件时唤醒
C-C:获取事件值以将其返回
C-D:清除事件
您在生产者与消费者之间或消费者与彼此之间不执行任何订购,因此可能会发生这种情况:
P-A(事件清楚)
C1-A
C2-A
C3-A(三个消费者都在等待)
P-B(事件设定)
C1-B
C2-B
C3-B(所有消费者因事件设定而醒来)
C1-C(消费者1将事件视为设定)
C1-D(消费者1已清除事件)
C2-C(消费者2认为事件清楚)
C3-C(消费者3认为事件清楚)
C2-d
C3-d
......