Before looking at the Greenlet just provides the basic Coroutine function, is the smallest execution unit. But to use it, you also need to provide a scheduler to schedule when and which Greenlet should be executed. So I looked at the realization of gevent, The current stable version uses an alternative to libev.libevent. Better performance. Libev supports many event types, but the most common is the IO and timer type of. IO types via system-provided related system call implementations (Linux is Epoll), The timer type is implemented by maintaining a minimal heap.
Take a look at the following code:
Python code
Import gevent from gevent import Monkey Monkey.patch_all () def download (): import urllib2 Urllib2.urlopen (' http://www.google.com/'). Read () c = gevent.spawn (download) gevent.joinall ([C])
Gevent Create and start a greenlet with spawn, this greenlet execution function is download. Start this greenlet by adding this greenlet to Libev Callback inside. Libev calls the function inside the prepare callback every time the event loop executes, and then clears the callback from the inside. This will ensure that every spawn has an opportunity to execute. And it will be executed only once.
When this greenlet executes Urlopen and read, it involves IO operations (socket.[ SEND|RECV]), gevent These functions by monkey Patch, and when the associated operation is invoked, a watcher of the corresponding FD is added to the list of events in Libev.
When a related read-write event occurs, the corresponding callback is triggered. The associated callback calls the Greenlet switch for coroutine switching.
The Greenlet achieves the purpose of the scheduler through the above method.