Python gevent Implementation Mechanism

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.