Using gevent monkey patching with threading makes thread work serially Using gevent monkey patching with threading makes thread work serially multithreading multithreading

Using gevent monkey patching with threading makes thread work serially


When threads are monkey patched in gevent, they behave as coroutines. This means that you have to explicitly yield control to make it possible for other coroutines to execute.

The way to do this is call a blocking operation that has been patched (this will yield automatically) or gevent.sleep:

#!/usr/bin/env pythonfrom gevent import monkey, sleepmonkey.patch_all()import threadingclass ExampleThread(threading.Thread):    def run(self):        for i in xrange(10):            print 'working'            sleep()if __name__ == '__main__':    worker = ExampleThread()    worker.start()    print 'this will be printed after the first call to sleep'


You can leave your Thread-based class in place if you substitute the Thread with Greenlet, for example like this:

from gevent import monkeyfrom gevent import Greenletfrom threading import Threadclass ThreadLikeGreenlet(Greenlet):    def __init__(self, name=None, target=None, args=(), kwargs=()):        super().__init__(target, *args, **dict(kwargs))        self.name = namedef is_gevent_patched():    return monkey.is_module_patched('threading')if is_gevent_patched():    Thread = ThreadLikeGreenlet  # substitute Thread with Greenletclass ExampleThread(Thread):    ...

it will work as you wish then.