There are times when serving requests needs to be controlled without forcibly killing a running server instance. It is possible to do this with Python’s gevent library. In this article, we will examine how to control the gevent StreamServer through an event.
All code is available on my Github through an actor system project which I intend to use in production (e.g. it will be completed).
Gevent utilizes green threads through the gevent.greenlet package. A greenlet, a Green thread in gevent, utilizes a similar API to the Python asyncio library but with more control over scheduling.
The greenlet is scheduled by the program instead of the OS and works more akin to threading in the JVM. Greenlet threads run code concurrently but not in parallel, although this could be achieved by starting greenlets in a new process.
In this manner, it is possible to schedule Greenlet threads on a new operating system based thread or, more likely due to the GIL, in a new process to achieve a similar level of concurrency and even parallelism to Java. Of course, the cost of parallelism must be considered.
Gevent maintains a server through gevent.server.StreamServer. This server utilizes greenlet threads to concurrently handle requests.
A StreamServer takes an address and port and can optionally be given a pool for controlling the number of connections created:
pool = Pool(MAX_THREADS) server = StreamServer((self.host, self.port), handle_connect, spawn=pool)
This concurrency allows for faster communication in the bi-directional way that troubles asyncio.
Gracefully Exiting a StreamServer
In instances where we want to gracefully exit a server while still running code, it is possible to use the gevent.event.Event class to communicate between threads and force the server to stop.
As a preliminary note, it is necessary to call the gevent.monkey.patch_all method in the native thread to allow for cross-thread communications.
from gevent import monkey monkey.patch_all()
Instead of using the serve_forever method, we must utilize the start and stop methods. this must also be accompanied by the use of the Event class:
evt = Event() pool = Pool(MAX_THREADS) server = StreamServer((self.host, self.port), handle_connect, spawn=pool) server.start() gevent.signal(signal.SIGQUIT, self.evt.set) gevent.signal(signal.SIGTERM, self.evt.set) gevent.signal(signal.SIGINT, self.evt.set) self.signal_queue.put(ServerStarted()) atexit.register(self.__server.stop) evt.wait() server.stop(10)
For good measure, termination signals are handled through gevent.signal to allow the server to close and kill the thread in case of user based termination. This hopefully leaves no loose ends.
The event can be set externally to force the server to stop with the preset 10 second timeout:
In this article, we examined how a greenlet thread or server can be controlled using a separate thread for graceful termination without exiting a running program. An Event was used to achieve our goal.