跑第二个zmq.eventloop.ioloop

2024-05-13 10:58:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在后台线程中创建一个pyzmqeventloop,并让它能够与独立的Python脚本和IPython脚本一起正常工作。(IPython使用位于主线程中的PyZMQ eventloops,因此这给我带来了一些问题,以及为什么我要在后台线程中启动一个私有ioloop。)

我想在线程A中运行代码,同时让PyZMQ eventloop句柄从线程B中的套接字接收数据。在线程A中,有时我需要等待线程B中的事件集

我怎样才能让它工作?如果我试着用IPython,似乎有点不对劲:

from zmq.eventloop import ioloop
import threading

class IOBackgroundLoop(object):
    def __init__(self):
        self._loop = None
        self._thread = threading.Thread(target=self.run)        
        self._thread.daemon = True
        self._started = threading.Event()
    @property
    def loop(self):
        return self._loop
    def run(self):
        self._loop = ioloop.IOLoop()
        self._loop.initialize()
        self._loop.make_current()
        self._started.set()
        self._loop.start()
    def start(self):
        self._thread.start()
        self._started.wait()

bkloop = IOBackgroundLoop()
bkloop.start()
for loop in [bkloop.loop, ioloop.IOLoop.instance()]:
    print "%s running: %s" % (loop, loop._running)

这将打印出IOLoop的两个独立实例,但是如果我使用它,它似乎就不起作用了。我想不出一个小的示例程序来演示这一点;我尝试了一个超时函数:

^{pr2}$

我得到的结果是(没有“嗨”:

1412889057.68: here
1412889059.68: there
1412889059.68: here
1412889061.68: there

当我按另一个shift+Enter键时,我得到

1412889061.68: hi from <zmq.eventloop.ioloop.ZMQIOLoop object at 0x000000000467E4E0>

这是主线程中的IOLoop对象,但我的私有实例IOLoop从不打印hi。在

我会做错什么?在


Tags: self脚本loopdefipythoneventloop线程thread
1条回答
网友
1楼 · 发布于 2024-05-13 10:58:31

呃,我刚在龙卷风文档里注意到了这一点:

Note that it is not safe to call add_timeout from other threads. Instead, you must use add_callback to transfer control to the IOLoop's thread, and then call add_timeout from there.

似乎还需要将zmq.eventloop.zmqstream设置在与ioloop相同的线程中才能正常工作。在

相关问题 更多 >