Search code examples
pythongevent

What is greenlet?


I am new to gevent.I have read introduction from gevent

They have provided simple examples but I am struggling to understand what greenlet is.From Learning Concurrency.

Greenlets are a very lightweight coroutine written in C that
are cooperatively scheduled. They provide us with a very lightweight thread-
like object that allows us to achieve concurrent execution within our Python
programs without incurring the cost of spinning up multiple threads.

Greenlets are not threads? How is synhronisation point defined? Could somone explain with examples?


Solution

  • Synchronous programming can only do one thing at a time. So while a database query is running, everyone else (say pulling up a webpage via a web framework) has to wait for that to finish.

    Gevent makes it Asynchronous by using context switching and events. What does this mean? Think of it like this. You have a queue with stuff waiting for things to happen, meanwhile gevent says, ok you can wait, I am going to move to the next task and start doing stuff while I am waiting for you to finish (like a database read, or waiting for user input) and when you are done, when I go back through my queue and you say you're ready for the next step, I focus on that for you.

    In this way, though still single threaded, the application can be switching between jobs super fast, constantly checking the status to see if it deserves focus or not, meanwhile, other things can get done while it waits for you.

    As opposed to multiple threads, that are handled by the OS and heavy, they require their own resources and are expensive to switch between.

    Gevent makes converting stuff that would normally use threading to greenlets easy.