【问题标题】:Multithreading and ZMQ DEALER/REP hello world doesn't work多线程和 ZMQ DEALER/REP hello world 不起作用
【发布时间】:2023-03-14 07:22:01
【问题描述】:

首先是我的代码(很大程度上来自 ZMQ doc http://zguide.zeromq.org/py:mtserver):

import zmq
import time
import sys
import threading

#SOCKET_NAME = "tcp://127.0.0.1:8000"
SOCKET_NAME = "inproc://mysocket"

def dealerRoutine(context):
    socket = context.socket(zmq.DEALER)
    socket.bind(SOCKET_NAME)
    time.sleep(12)
    socket.send("hello")
    socket.send("hello")
    print socket.recv()
    print socket.recv()
    socket.close()


def workerRoutine(context):
    socket = context.socket(zmq.REP)
    socket.connect(SOCKET_NAME)
    s = socket.recv()
    print s
    socket.send("world")

context = zmq.Context()

workers = []
for i in range(0, 2):
    worker = threading.Thread(target=workerRoutine, args=([context]))
    workers.append(worker) 
    worker.start()

dealerRoutine(context)

for worker in workers:
    worker.terminated = True

context.term()

我已经用 inproc 和 tcp 套接字尝试了这段代码。

  • inproc 在工作人员尝试连接时出错
  • TCP 只是在经销商发送后等待,工人没有打印,经销商没有收到其他消息
  • 我已经想到了慢连接器问题并添加了一个睡眠(一个在工人连接之前,一个在经销商的 send() 之前):这只会导致 inproc 的行为与 TCP 相同。

PS : 我对 camelCase 感到抱歉,但我对它上瘾了。

【问题讨论】:

    标签: python zeromq pyzmq


    【解决方案1】:

    我通过以下方式使其工作:

    • 对于经销商,多部分发送您的消息,第一部分为空消息,第二部分为您的消息
    • 减少了计时器(虽然没有帮助)

    代码如下:

    import zmq
    import time
    import sys
    import threading
    
    SOCKET_NAME = "tcp://127.0.0.1:8000"
    #SOCKET_NAME = "inproc://mysocket"
    
    def dealerRoutine(context):
        socket = context.socket(zmq.DEALER)
        socket.bind(SOCKET_NAME)
        time.sleep(1)
        socket.send("", zmq.SNDMORE)
        socket.send("hello")
        socket.send("", zmq.SNDMORE)
        socket.send("hello")
        print socket.recv()
        print socket.recv()
        socket.close()
    
    
    def workerRoutine(context):
        socket = context.socket(zmq.REP)
        socket.connect(SOCKET_NAME)
        s = socket.recv()
        print s
        socket.send("world")
    
    context = zmq.Context()
    
    workers = []
    for i in range(0, 2):
        worker = threading.Thread(target=workerRoutine, args=([context]))
        workers.append(worker) 
        worker.start()
    
    dealerRoutine(context)
    
    for worker in workers:
        worker.terminated = True
    
    context.term()
    

    【讨论】:

    • 谢谢,我在专门用于 0 MQ 的 IRC 上得到了 minrk 的帮助,问题是多部分消息。读者可能会使用 send_multipart(['', 'hello']) ,这与您使用 zmq.SNDMORE 标志所做的相同。
    • 我认为这段代码中还有另一个错误。对于发送给它的所有内容,dealerRoutine 需要 两次。因此,在这种情况下,它需要 4 个 print socket.recv() 语句……如果您尝试一下,您会发现它只在第二次和第四次打印时打印“世界”。不过,我还没有找到 ZMQ 中记录的位置。
    猜你喜欢
    • 2018-02-17
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多