Reputation: 1668
Is there a way to know from which greenlet the current greenlet was spawned from in gevent?
My use case is: I have a server which handles requests to execute python code (yes, yes, it is unsafe I know :-). Each request spawns a greenlet which handles the request, including redirecting any input, output or error to a channel private to the request. I want to be able to handle requests concurrently and the requests may spawn greenlets themselves.
You can find an example of what I am trying to do here
Upvotes: 1
Views: 959
Reputation: 1242
In original greenlet
package, creating new greenlet object has the following signature greenlet(run=None, parent=None)
. So it means that you can provide parent
argument or keep it None
and greenlet assigns caller function by default.
On top of this package, gevent provides tools and tiny event loop that orchestrates greenlets behaviour and lifecycle . So any greenlet that is created by gevent.spawn
or gevent.Greenlet
automatically inherits current hub (event loop) as a parent. So every time when one greenlet finishes its execution, it transfer control back to event loop. According to documentation: "This allows a greenlet to take some cleanup actions before yielding control."
However, looking in documentation and source code of Greenlet initialization, I see that is still possible to override constructor by providing new arguments.
from gevent.greenlet import Greenlet as GeventGreenlet
class Greenlet(GeventGreenlet):
def __init__(self, caller=None, *args, **kwargs):
super(Greenlet, self).__init__(*args, **kwargs)
self._caller = caller
Then you need to tell greenlet package to use your Greenlet implementation (similar to gevent monkeypatch) as early as possible.
import gevent.greenlet
from myapp.greenlet import Greenlet
gevent.greenlet.Greenlet = Greenlet
Upvotes: 1