我的项目正在使用 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/