title: Implementing virtual threads without cheating
body: <p>In the <a href="http://sdiehl.github.io/gevent-tutorial/" rel="nofollow">gevent tutorial</a> there's an example that looks like this:</p>
  
  <pre><code>import gevent
  
  def foo():
      print('Running in foo')
      gevent.sleep(0)
      print('Explicit context switch to foo again')
  
  def bar():
      print('Explicit context to bar')
      gevent.sleep(0)
      print('Implicit context switch back to bar')
  
  gevent.joinall([
      gevent.spawn(foo),
      gevent.spawn(bar),
  ])
  </code></pre>
  
  <p>and the output is</p>
  
  <pre><code>Running in foo
  Explicit context to bar
  Explicit context switch to foo again
  Implicit context switch back to bar
  </code></pre>
  
  <p>I've tested it and seen for myself that it works.  A friend of mine claims this is run entirely within a single thread. Except that I can't think of any implementation of gevent.sleep(0) which doesn't boil down to some form of "cheating" (ie: Swap the top two stack frames etc.)</p>
  
  <p>Can someone explain how this works?  If this were Java (or at least some language where that kind of stack manipulation is forbidden), would this be possible? (again, without using multiple threads).</p>