简体   繁体   中英

gevent find parent greenlet

Is there a way to know from which greenlet the current greenlet was spawned from in gevent?

  1. I realize that the greenlet which spawned the current greenlet might have terminated already, but in that case I would be ok with handling a None as an answer.
  2. I am aware of gevent.Greenlet.parent but this represents only the hub, not the direct greenlet from which the current greenlet was started from
  3. I would prefer a solution that does not involve monkey patching gevent.Greenlet

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM