【发布时间】:2014-02-21 09:42:53
【问题描述】:
ZeroMQ 指南指出套接字不应在线程之间共享。然而,在Pyre ZeroMQ 项目中,在zhelper 模块的某个时刻,在线程中创建了一个套接字,然后在新线程中使用:
def zthread_fork(ctx, func, *args, **kwargs):
"""
Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error.
"""
a = ctx.socket(zmq.PAIR)
a.linger = 0
b = ctx.socket(zmq.PAIR)
b.linger = 0
a.set_hwm(1)
b.set_hwm(1)
iface = "inproc://%s" % binascii.hexlify(os.urandom(8))
a.bind(iface)
b.connect(iface)
thread = threading.Thread(target=func, args=((ctx, b)+args), kwargs=kwargs)
#thread.daemon = True
thread.start()
return a
如果创建者线程实际上没有调用任何套接字函数,是否可以在一个线程中创建一个 ZeroMQ 套接字,然后在另一个线程中使用它?
【问题讨论】:
-
如果跨线程共享可能会导致锁/问题。但从技术上讲,这是可能的。我建议不要这样做,但如果你有你的头脑,它应该是可能的。
-
只是出于好奇,是什么阻碍了您在新线程中创建套接字?
-
没什么,这是我在自己的代码中所做的。但是,此示例是来自官方 ZeroMQ 项目的示例。这就是为什么我在这里有点困惑,因为它似乎没有遵循通常的建议。
标签: python multithreading networking thread-safety zeromq