如何在python的线程中运行zeroRpc服务器?

问题描述:

我在启动python中的zeroRPC服务器时遇到问题。我按照official example这样做了,但是当我调用run()方法时,它在无限循环中工作,所以启动这个服务器后我的程序无法继续。我试图在新的线程中运行它,但我有以下异常:如何在python的线程中运行zeroRpc服务器?

LoopExit: ('This operation would block forever', <Hub at 0x7f7a0c8f37d0 epoll pending=0 ref=0 fileno=19>)

我真的不知道如何解决它。有什么想法?

+1

我想你已经误解了这是为了什么。当然,它会阻止,它正在等待收到消息。为什么你想让程序“继续”? –

+0

因为这是一个更大的项目,与第二方的沟通只是其中的一部分。我还与HW(arduino)进行通信,它在自己的线程中工作,所有的通信都应该由主脚本控制。我不知道,也许这只是糟糕的应用程序设计,你认为我应该怎么处理它? @DanielRoseman –

总之,你不能使用OS线程与zerorpc。

较长的答案:zerorpc-python使用gevent进行IO。这意味着您的项目必须使用gevent并与其兼容。本地操作系统线程和gevent协程(也称为greenlet,绿色线程等)并不真正成为朋友。

gevent中有一个本地线程池选项(http://www.gevent.org/gevent.threadpool.html)。

你不能派生一个本地操作系统线程并在那里运行gevent协程(包括zerorpc)。

如果你正在做GEVENT协程的作品,然后,而不是在本地线程运行run(),在GEVENT协程/ greenlet/greenthread像这样运行:

# starts the server in its own greenlet 
gevent.spawn(myserver.run) 
# zerorpc will spawn many more greenlet as needed. 
# they all need to run cooperatively 

# here we are continuing on the main greenlet. 
# as a single greenlet can execute at a time, we must never block 
# for too long. Using gevent IOs will cooperatively yield for example. 
# Calling gevent.sleep() will yield as well. 
while True: 
    gevent.sleep(1) 

注:如果当gevent不是一种选择,解决方案是实现zerorpc-python版本,它不使用gevent并在Python之外实现它的IO,但这有一个有趣的复杂性,而且很快就不会发生。