Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Event loop w/ gevent

Tags:

python

gevent

import gevent
from gevent.event import AsyncResult
import time

class Job(object):
    def __init__(self, name):
        self.name = name

def setter(job):
    print 'starting'
    gevent.sleep(3)
    job.result.set('%s done' % job.name)

def waiter(job):
    print job.result.get()


# event loop
running = []
for i in range(5):
    print 'creating'
    j = Job(i)
    j.result = AsyncResult()
    running.append(gevent.spawn(setter, j))
    running.append(gevent.spawn(waiter, j))

print 'started greenlets, event loop go do something else'
time.sleep(5)
gevent.joinall(running) 

gevent doesnt actually start until joinall is called

  • Is there something that would start/spawn gevent asynchronously (why does it not start right away as soon as spawn is called)?
  • Is there a select/epoll on running greenlets to see which one needs to be joined instead of joinall()?
like image 780
ealeon Avatar asked Aug 13 '26 11:08

ealeon


1 Answers

No, it does not start straight away. It will start as soon as your main greenlet yields to the hub (releases control by calling sleep or join for example)

Clearly your intention is that it starts when you call time. It does not, because you have not monkey patched it.

Add these lines to the very top of your file:

from gevent import monkey
monkey.patch_all()

This will then have the behaviour that you want (because under the hood, time will be modified to yield to the hub).

Alternatively, you can call gevent.sleep.

like image 66
DevShark Avatar answered Aug 15 '26 21:08

DevShark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!