[BangPypers] real use case of gevent context switch gevent.sleep(0)

Noufal Ibrahim KV noufal at nibrahim.net.in
Sat Jun 20 20:22:34 CEST 2015

On Sat, Jun 20 2015, anu sree wrote:

> Hi,
> I have seen an example of gevent context switch
> http://sdiehl.github.io/gevent-tutorial/#synchronous-asynchronous-execution
> Could you please give some real use case with example.
> It would be fine If you can share link of github project which uses gevent
> context gevent.sleep(0).


The difference between a regular sleep and a gevent sleep is that the
gevent sleep will not make the whole interpreter process sleep. It will
instead, only make the current greenlet sleep which essentially tells
the internal scheduler to not execute it till the time is over. 

You can see this happen like this. Make a greenlet in your interpreter
like so

>>> from gevent import Greenlet
>>> class Printer(Greenlet):
...   def _run(self):
...       n = 0
...       while True:
...          n += 1
...          print n

This simply prints numbers starting from 1.

now you can create this greenlet and start it

>>> p = Printer()
>>> p.start()

Nothing will happen. This is cooperative multitasking where the current
Greenlet (your interpreter shell) has to "give up" its time slice and
let p execute. You can do this by monkey patching sleep

>>> from gevent import monkey
>>> monkey.patch_time()
>>> import time
>>> time.sleep(1)

Now, control is handed over to the Greenlet. However, it is not
cooperative and runs a tight loop without ever giving up control. This
means, that you'll never be able to execute your own interpreter again.

So you see, the various greenlets have to "cooperate" to get things
done. This is in counter distinction to how preemptive multitasking
works where the OS can force the currently executing thread or process
to stop and then grant execution to something else. They don't need to
be nice.

If your greenlet looked like this

>>> class Printer(Greenlet):
...    def _run(self):
...       n = 0  
...       while True:
...         n += 1
...         time.sleep(0.1)
...         print n

the slot would be given up inside each iteration and other greenlets can
execute. Try it. 

So people stick in a call to a monkey patched version of sleep inside
tight loops to suspend the current interpreter for a short period of
time thereby letting other greenlets execute. 

Krace's example is a good one.


More information about the BangPypers mailing list