python - gevent,触发新生成的任务运行的方法

标签 python thrift gevent

我的项目正在使用 gevnet(这对我来说是新的)来实现 Thrift 服务器。

我正在阅读代码并从其文档中学习。下面的代码片段在我的项目中:

TSocket.socket = gevent.socket # I find this when comparing the production
                               # code and mine. It seems that this socket
                               # schedule the tasks when there are newly-spawn ones. 
                               # Could someone tell me more about it?

while True:
    try:
        client = self.serverTransport.accept()
        gevent.spawn(self._serve_client, client)
    except (SystemExit, KeyboardInterrupt):
        break
    except Exception as x:
        logging.exception(x)

生成后,直接在这里完成工作。

但是在我自己的实现中,为了自学,我必须执行以下操作:

while True:
    try:
        client = self.serverTransport.accept()
        gevent.spawn(self._serve_client, client)
        gevent.sleep(0)  # switch to the newly-spawn task.
                         # this makes it to process tasks one by one and
                         # this makes it non-concurrent
    except (SystemExit, KeyboardInterrupt):
        break
    except Exception as x:
        logging.exception(x)

在我的生产代码中,我没有找到任何关于如何触发任务运行的线索。 因此,我在这里询问有关在上面的服务器中运行新生成的任务的方法的一些信息。

最佳答案

在您的代码中,您必须调用 gevent.sleep(0) 因为没有其他方法 触发 gevent 循环。这样的 sleep 可以让你重新控制 gevent,执行生成的 greenlet。

生产代码中的行TSocket.socket = gevent.socket修补了 要使用的默认 Thrift 套接字实现 而是使用 gevent 套接字; gevent 套接字运行 gevent 循环,所以你真的 需要此补丁才能运行您的代码。

如果没有补丁,TSocket.socket 会阻塞并终止并发 (没有操作系统级线程)。

关于python - gevent,触发新生成的任务运行的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31021536/

相关文章:

python - 来自 numpy.linalg.svd 的大型矩阵的 MemoryError

python - 索引 1 超出轴 0 的范围,决策树分类的大小为 1 错误

python - 以 JSON 格式发送 OpenCV 图像

javascript - 使用服务器 Java 和 Javascript 客户端的 Apache Thrift 数组

java - Thrift TSimpleServer 在多次成功请求后变得无响应

java - Thrift 列表的序列化(反序列化)

python - 为什么我们需要 gevent.queue?

python - 使用 Pandas 从字符串列表中提取某些元素并转换为日期时间

具有多线程的 Python 请求

python - 使用 'yield' 进行上下文切换