Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Simple Async in Python with Gevent

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

In my last post I spoke about concurrency with asyncio. Now what if you don’t want to concern yourself with async/await practices and just want to write synchronous code that executes I/O asynchronously? That’s where the library gevent comes in. It does this by modifying Python’s standard library during runtime to call it’s own asynchronous versions.

Last post code’s example written in gevent.

# The first two lines must be called before
# any other modules are loaded
import gevent
from gevent import monkey; monkey.patch_all()

import time

def think(duration):
    print("Starting to think for " + str(duration) + " seconds...")
    print("Finished thinking for " + str(duration) + " seconds...")

    gevent.spawn(think, 5),
    gevent.spawn(think, 2)

Notice that the function think is written the same as the synchronous version.

gevent is written on top of C libraries libev or libuv . This combined with the monkey patching can make gevent based applications hard to debug if something goes wrong. Otherwise it’s a great tool to quickly take advantage of concurrency.

Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :