Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use loop.run_forever? #17

Open
jaklaassen-affirm opened this issue Feb 13, 2024 · 0 comments
Open

How to use loop.run_forever? #17

jaklaassen-affirm opened this issue Feb 13, 2024 · 0 comments

Comments

@jaklaassen-affirm
Copy link

jaklaassen-affirm commented Feb 13, 2024

Hi, this project is great! Thanks for putting it together.

I've been experimenting with running asyncio functions in gevent with loop.run_forever. I had trouble getting the asyncio loop to actually run any scheduled tasks because the event loop would never be notified when create_task is called because calling create_task does not notify selector.select. I was able to resolve this by making EventLoop.call_soon call self._write_to_self() in the same way that EventLoop.call_soon_threadsafe does, to notify the selector.

Something like this:

class GeventEventloop(asyncio.SelectorEventLoop):
    def __init__(self, selector=None):
        super(GeventEventloop, self).__init__(selector or gevent.selectors.DefaultSelector())

    def call_soon(self, callback, *args, context=None):
        handle = super(GeventEventloop, self).call_soon(callback, *args, context=context)
        self._write_to_self() # Without this, it never runs the task function
        return handle


loop = GeventEventloop()
loop_greenlet = gevent.spawn(loop.run_forever)
loop_greenlet.start()


async def logit(text):
    print(text)

def callit(fn, *args):
    task = loop.create_task(fn(*args))
    event = gevent.event.Event()
    def done(_):
        event.set()
    task.add_done_callback(done)
    event.wait()
    return task.result()

greenlets = []
for i in range(20):
    greenlets.append(gevent.spawn(callit, logit, "meow"))

gevent.wait(greenlets)

I'm curious if I'm doing something wrong, or if there is something useful to add to the framework or docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant