Книга: Learning Concurrency in Python
Назад: Event loops
Дальше: Simple example-hostnames

Greenlets

The core of the gevent framework is the greenlet. Greenlets, if you haven't worked with them before, 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.

These lightweight pseudo threads are spawned by the creation of a greenlet instance and subsequently call its start method. These lightweight pseudo threads then execute a certain amount of code before cooperatively giving up control and allowing another pseudo thread to then take over. This cycle of repeated work and then giving up is repeated over and over again until the program has accomplished it's target and terminated.

We can define greenlets through the use of functions such as spawn as follows:

import gevent

def
myGreenlet():
print("My Greenlet is executing")

gevent.spawn(myGreenlet)
gevent.sleep(1)

Alternatively, we can also define them through the use of sub-classing as follows:

import gevent
from gevent import Greenlet

class
MyNoopGreenlet(Greenlet):

def __init__(self, seconds):
Greenlet.__init__(self)
self.seconds = seconds

def _run(self):
print("My Greenlet executing")
gevent.sleep(self.seconds)

def __str__(self):
return 'MyNoopGreenlet(%s)' % self.seconds

g
= MyNoopGreenlet(4)
g.start()
g.join()
print(g.dead)
Назад: Event loops
Дальше: Simple example-hostnames