我想知道在pyzmq中是否有一个线程本地ioloop。代码中的注释是(https://github.com/zeromq/pyzmq/blob/master/zmq/eventloop/minitornado/ioloop.py第172行):
通常,在构造异步对象时,您应该使用
IOLoop.current作为缺省值,当您打算从另一个线程与主线程通信时,应该使用IOLoop.instance。
根据这一点,我假设使用.current可以创建线程本地ioloop,可以独立于主线程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()为两个循环打印相同的ids:
main id(loop): 33576144
w.__init__ id(loop): 33576144
w.__run__ id(loop): 33576144
current: 33576144我很高兴能理解我错过了什么。
亚历克斯
发布于 2015-06-12 16:30:11
由于历史原因,IOLoop.current()有一些怪癖。如果存在线程本地事件循环,它将引用它,但它不会创建线程本地事件循环,而是返回到单例(主线程)循环。
解决方案是在w.__init__() (self.loop = ioloop.IOLoop())中创建一个新的循环,并使其在w.run() (self.loop.make_current() )中流通。loop.start()会为你打电话给make_current() )。
https://stackoverflow.com/questions/30779019
复制相似问题