Search code examples
pythongevent

python gevent.event.Event


After i read the Gevent Tutorial, i have a question about the gevent.event.Event. Does the Event.set() will wake up all the function which is blocked by Event.wait() ?
Just like the following code:

import gevent
from gevent.event import Event
evt = Event()

def setter():
    print('In setter')
    gevent.sleep(3)
    print("After first sleep")
    evt.set()     #first set
    print 'second sleep'
    gevent.sleep(3)
    evt.set()     #second set
    print 'end of setter'

def waiter():
    print("in waiter")
    evt.wait()     #first wait
    print 'after first wait'
    evt.wait()     #second wait
    print 'end of waiter'

gevent.joinall([
    gevent.spawn(setter),
    gevent.spawn(waiter),
])

When i run this code, i found the first set in function 'setter' will wake up all the wait in function 'waiter'. But what i need is first set wake up the first wait and then the second set wake up second wait. In my opinion, evt.wait() will be blocked only when evt.set() call, Does my understanding of gevent.event.Event() correctly ? How to realize my idea ?


Solution

  • gevent.event.Event works exactly like the threading.Event Python object. So, once it is set, it wakes up waiters and stays set forever (except if .clear() is called).

    What you want to achieve can be done like this:

    def setter():
        print('In setter')
        gevent.sleep(3)
        print("After first sleep")
        evt.set()     #first set
        ### now clear evt
        evt.clear()
        ###
        print 'second sleep'
        gevent.sleep(3)
        evt.set()     #second set
        print 'end of setter'