【问题标题】:Moving a ZeroMQ socket to another thread将 ZeroMQ 套接字移动到另一个线程
【发布时间】: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


【解决方案1】:

当您在其间设置内存屏障时,您可以将套接字传递给另一个线程。锁和其他同步原语使用内存屏障,所以是的,您可以使用任何同步原语来包装您的套接字。

然而,我想指出的是,必须将套接字包装在互斥体中通常表明您的架构有问题。您应该做的是设置多个 inproc 套接字,每个线程拥有一个或多个套接字,并让线程通过这些 inproc 套接字相互通信,而不是使用互斥体交换套接字。

【讨论】:

  • 我同意。此外,该指南提到(对不起,我找不到确切的链接)上下文是线程安全的,但套接字不是。正如您所说,最好使用inproc:// 目标在进程之间进行通信。它还有助于您的可扩展性,这是重点。 :)
猜你喜欢
  • 2017-06-15
  • 1970-01-01
  • 2014-11-19
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多