Eventlet与Python守护进程,Foo未被调用?

2 投票
2 回答
1058 浏览
提问于 2025-04-16 20:56

我正在尝试创建一个Python守护进程,它会监听一个队列(使用Redis Kombu)。然后抓取任务并启动一个绿色线程来处理这个任务。

我可以顺利接收到任务并处理它,但当我尝试用eventlet启动一个绿色线程时,似乎什么都没有发生。

没有任何打印输出,也没有日志显示。

class agent(Daemon):
    """
    Agent
    """
    def run(self):  
        # Setup connection
        mainLogger.debug('Connecting to Redis')
        connection = BrokerConnection(
                        hostname=agentConfig['redis_host'],
                        transport="redis",
                        virtual_host=agentConfig['redis_db'],
                        port=int(agentConfig['redis_port']))
        connection.connect()

        # Create an eventlet pool of size 5
        pool = eventlet.GreenPool(5)
        q = connection.SimpleQueue("myq")
        while True:
            try:
               message = q.get(block=True, timeout=1)
               print "GOT A MESSAGE FROM Q !"
               pool.spawn_n(self.foo, 'x')
               print "END SPAWN !"
            except Empty:
               mainLogger.debug('No tasks, going to sleep')
               time.sleep(1)


    def foo(self, x):
        mainLogger.debug('\o/')
        print "HELLO FROM SPAWN"

我是不是做错了什么?

2 个回答

2

你只需要使用 eventlet.sleep,具体的用法可以在这里找到:

http://eventlet.net/doc/basic_usage.html#eventlet.sleep

3

我需要调用 eventlet.monkey_patch(),这样才能让 sleep() 这个函数能够进行上下文切换。

撰写回答