Stephan
Stephan

Reputation: 3799

gevent control greenlets with events

Let say I have an Event() coming in and there are a X number of greenlets waiting for the event. When those waiting greenlets are done I want to do a Publish()

How do I know when to publish?

schematic:

event.set() -> X number event.wait() -> finally publish the current state.

How do I make sure that all greenlets who wait() are done before I do a publish?

I think putting all the waiting greenlets in a Group and do a group.join() could work.

import gevent
from gevent.pool import Group
from gevent.event import Event
import random

incoming = Event()

group = Group()

def test_wait(x):
    gevent.sleep(random.random() * 3)
    print 'test %s' % (x)

def publish():
    print 'published' 


for x in range(int(random.random() * 20)):
    group.spawn(test_wait, x)


def event_setter():
    incoming.set()
    gevent.sleep(0)                                                                                                                      
    publish()


event_setter()

Gevent.sleep(0) works if there is no sleep in the test_wait. How can I be sure all waiting greenlets have ended?

Upvotes: 3

Views: 1279

Answers (2)

arilou
arilou

Reputation: 475

If you use group.join() instead of gevent.sleep(0) in event_setter(), you can see the desired result, like this:

Group size: 10
test 6
test 9
test 3
test 7
test 1
test 4
test 0
test 5
test 2
test 8
published

"Group size: 10" printed by the line: print "Group size: %d" % (len(group),)

Upvotes: 0

sloth
sloth

Reputation: 101072

You can put all greenlets into a list and call gevent.joinall(your_greenlets). The documentation is a bit spare, but there's an example.

Upvotes: 3

Related Questions