15

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)

Cœur
  • 37,241
  • 25
  • 195
  • 267
squirrel
  • 5,114
  • 4
  • 31
  • 43
  • We need more details of your implementation of greenlets. Are you using a pool, f.e.? Maybe ```gevent.shutdown()``` works for you? – dorvak Nov 05 '13 at 10:23
  • 1
    Most modules are going to use simply `gevent.spawn()`, but some might be using a pool or whatever they like. Also, there is no `gevent.shutdown()` in 1.0.0, and even if there were, it cannot be run from a non-main greenlet, and signal handler is more than likely to end up in a different one. – squirrel Nov 05 '13 at 13:58

2 Answers2

20

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)])
Community
  • 1
  • 1
kkurian
  • 3,844
  • 3
  • 30
  • 49
3

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)]
)
sas
  • 7,017
  • 4
  • 36
  • 50