Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a gevent application, how can I kill all greenlets that have been started?

Tags:

python

gevent

I have a gevent application that spawns multiple greenlets across multiple modules. I want to be able to gracefully shutdown the application (either internally or by catching SIGTERM, for instance), allowing greenlets to terminate nicely by catching GreenletExit and executing finally: clauses.

If I had the a of all running greenlets, I could do gevent.killall(list_of_greenlets), but maintaining such a list is rather a hassle; besides, gevent must be keeping this very list in some form or another.

So, can I kill all greenlets that have been started without maintaining a list of them?

(I'm using gevent 1.0.0 on python 2.7 on raspbian)

like image 596
squirrel Avatar asked Nov 05 '13 02:11

squirrel


2 Answers

According to another SO answer, it's possible "to iterate through all the objects on the heap and search for greenlets." So, I imagine this ought to work:

import gc
import gevent
from greenlet import greenlet    
gevent.killall([obj for obj in gc.get_objects() if isinstance(obj, greenlet)])
like image 110
kkurian Avatar answered Oct 24 '22 09:10

kkurian


This didn't quite work for the versions of gevent (1.2.2) and greenlet (0.4.13) I was using but the following does:

import gc
import gevent
gevent.killall(
    [obj for obj in gc.get_objects() if isinstance(obj, gevent.Greenlet)]
)
like image 31
sas Avatar answered Oct 24 '22 09:10

sas