2

Greenlet.spawn按照文档中的定义创建一个新的 Greenlet 实例。我有下面的代码,我希望能够通过它的 id 杀死一个 Greenlet。

import gevent
from gevent import Greenlet
from gevent import getcurrent

class BidTask(Greenlet):
    """ A new bid task creates a new thread when initialized """
    def __init__(self, bid):
        Greenlet.__init__(self)
        self.bid = bid

    def task(self):
      while True:
        print("Running %r" % [self.bid, id(getcurrent())])
        gevent.sleep(10) # sleep for 10 secs
        print("Running %r" % [self.bid, id(getcurrent())])

    def _run(self):
        self.task()

g = BidTask("Bid 1")
g.spawn("Bid 1") # a new instance of Greenlet is created

g2 = BidTask("Bid 2")
g2.spawn("Bid 2") # a new instance of Greenlet is created

gevent.joinall([g, g2])


# Elsewhere in another module
class Outsider(object):
  def kill(self, id):
    Greenlet.registry(id).kill() 

Outsider().kill(1234) # How to achieve this?

我感谢您的帮助。

4

0 回答 0