Skip to content

Instantly share code, notes, and snippets.

@hackaugusto
Last active June 8, 2020 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hackaugusto/2b58adda55b13429b92a829f09c071c0 to your computer and use it in GitHub Desktop.
Save hackaugusto/2b58adda55b13429b92a829f09c071c0 to your computer and use it in GitHub Desktop.
from gevent.monkey import patch_all
from gevent.lock import Semaphore
patch_all()
import aiogevent
import asyncio
import gevent
def aio_loop(coroutines):
asyncio.set_event_loop_policy(aiogevent.EventLoopPolicy())
for coroutine in coroutines:
asyncio.ensure_future(coroutine)
loop = asyncio.get_event_loop()
loop.run_forever()
loop.close()
class AGLock:
def __init__(self):
self.lock = Semaphore()
async def __aenter__(self):
await aiogevent.wrap_greenlet(gevent.Greenlet(self.lock.acquire))
async def __aexit__(self, _1, _2, _3):
await aiogevent.wrap_greenlet(gevent.Greenlet(self.lock.release))
def __enter__(self):
self.lock.acquire()
def __exit__(self, _1, _2, _3):
self.lock.release()
def g_run(i, lock):
with lock:
print(f"greenlet {i}")
async def aio_run(i, lock):
async with lock:
print(f"coroutine {i}")
def main():
lock = AGLock()
greenlets = []
coros = [aio_run(i, lock) for i in range(10)]
greenlets.extend(gevent.spawn(g_run, i, lock) for i in range(10))
greenlets.append(gevent.spawn(aio_loop, coros))
gevent.joinall(greenlets)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment