将 ZeroMQ 套接字移动到另一个线程 [英] Moving a ZeroMQ socket to another thread

查看:40
本文介绍了将 ZeroMQ 套接字移动到另一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ZeroMQ 指南指出不应在线程之间共享套接字.但是,在 Pyre ZeroMQ 项目中,在 zhelper 模块在线程中创建套接字,然后在新线程中使用:

The ZeroMQ guide states that sockets shouldn't be shared between threads. However, in the Pyre ZeroMQ project, at some point in the zhelper module a socket is created in a thread then used in a new thread :

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 套接字然后在另一个线程中使用它?

Is it okay to create a ZeroMQ socket in a thread and then use it in another thread if the creator thread doesn't actually call any socket functions ?

推荐答案

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

You can pass a socket to another thread when you put a memory barrier between. Locks and other synchronisation primitives use memory barriers, so yeah, you can use any synchronisation primitives to just wrap your socket.

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

What I would, however, like to point out is that having to wrap a socket in a mutex usually says that something is wrong with your architecture. What you should do is to set up multiple inproc sockets, each thread owning one or more sockets, and have the threads talk to each other via these inproc sockets rather than exchanging sockets using mutexes.

这篇关于将 ZeroMQ 套接字移动到另一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆