【问题标题】:Thread local pyzmq ioloop线程本地pyzmq ioloop
【发布时间】:2015-06-13 00:30:11
【问题描述】:

我想知道是否有办法在 pyzmq 中有一个线程本地 ioloop。代码中的注释说(https://github.com/zeromq/pyzmq/blob/master/zmq/eventloop/minitornado/ioloop.py 第 172 行):

一般情况下,您应该使用IOLoop.current 作为默认值 构造一个异步对象,并使用IOLoop.instance 当你的意思是从不同的主线程进行通信时 一个。

据此,我假设使用 .current 我应该能够创建线程本地 ioloop,我可以独立于主线程 ioloop 启动/停止。

奇怪的是,这不是我观察到的行为(我在本地线程中使用 .current,但在此循环上执行 .stop 也会停止主线程循环)。而且,这个简单的测试代码:

import threading
from zmq.eventloop import ioloop

loop = ioloop.IOLoop.current()
print 'main id(loop):', id(loop)

class w(threading.Thread):
    def __init__(self, loop=None):
        super(w, self).__init__()

        self.loop = loop or ioloop.IOLoop.current()

        print 'w.__init__ id(loop):', id(self.loop)

    def run(self):
        print 'w.__run__ id(loop):', id(self.loop)
        print 'current:', id(ioloop.IOLoop.current())


w(loop).start()

为两个循环打印相同的 id:

main id(loop): 33576144
w.__init__ id(loop): 33576144
w.__run__ id(loop): 33576144
current: 33576144

我很高兴知道我错过了什么。

亚历克斯

【问题讨论】:

    标签: python multithreading tornado pyzmq


    【解决方案1】:

    IOLoop.current() 由于历史原因有一些怪癖。如果存在,它将引用线程本地事件循环,但它不会创建一个,而是回退到单例(主线程)循环。

    解决方案是在w.__init__() (self.loop = ioloop.IOLoop()) 中创建一个新循环,并使其在w.run() 中成为当前循环(self.loop.make_current()loop.start() 将为您调用make_current())。

    【讨论】:

    • 谢谢,我会试试的。顺便说一句,IOLoop 不是单例类吗?
    • 在绝大多数情况下,每个进程只有一个 IOLoop,但在极少数情况下,拥有多个 IOLoop 很有用。
    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    • 2012-04-12
    • 2011-05-14
    • 2010-12-02
    相关资源
    最近更新 更多