Search code examples
pythongevent

What is monkeypatching with the python gevent library?


I'm reading through http://sdiehl.github.io/gevent-tutorial/ . In the example at the bottom of the page , I see:

import gevent.monkey
gevent.monkey.patch_socket()

I've read What is a monkey patch? , which gives a general discussion of monkey patching, but I don't understand why monkey patching is being referenced with gevent.


Solution

  • Gevent is a cooperative multitasking library. The way it works is you, the programmer, organise your code into units of work called greenlets. While a given greenlet is running, it runs alone. When it reaches a point where it would block, that is, it would have to wait for some external signal like a file, a timeout, our network data, the greenlet should cooperate by signaling gevent, who arranges for some other greenlet to run. The former greenish will be resumed once the data it waited for is ready. (This is the crayon-coloured gist of it, there may be some complexity that would be useful for you to know that is beyond the shore of this answer.)

    Now, Python's standard library is (was?) not cooperative. Rather than signaling gevent that a certain greenlet can be paused, the standard behaviour is to block selfishly. This causes a problem, since only the first greenlet is running: the others never get a chance to be scheduled.

    Enter money patching. The point of monkey.patch is to replace the blocking calls in the stdlib with cooperative alternatives, so that existing code can take advantage of the concurrency of greenlets without needing to be being rewritten.