Question

I wrote a script to play with gevent.event.Event but I found that the wait method seems not take effect. The version of gevent I use is 1.0.

My script is the following and you can also get it 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()

The output of the script is:
enter image description here

Was it helpful?

Solution

Your producers do the following:

P-A: Clear the event
P-B: Set the event

Your consumers do the following:

C-A: Wait for the event to become set
C-B: Wake up when event is set
C-C: Get the event value to return it
C-D: Clear the event

You enforce no ordering between your producer and your consumers or between your consumers and each other, so this can happen:

P-A (event is clear)
C1-A
C2-A
C3-A (all three consumers are waiting)
P-B (event is set)
C1-B
C2-B
C3-B (all consumers have woken up because the event is set)
C1-C (consumer 1 sees the event as set)
C1-D (consumer 1 has cleared the event)
C2-C (consumer 2 sees event as clear)
C3-C (consumer 3 sees event as clear)
C2-D
C3-D
...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top