Multithreading and ZMQ DEALER/REP hello world doesn't work

折月煮酒 提交于 2019-12-11 11:42:07

问题


First of all my code (largely inspired from 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()

I've tried this code with both inproc and tcp sockets.

  • inproc gives an error when workers try to connect
  • TCP just waits after the send on the dealer, no print appears from worker, no other message is received on dealer
  • I've thought of the slow joiner problem and add a sleep (one before the workers to connect, and one before dealer's send()) : that just causes the inproc to behave the same as TCP does.

PS : I'm sorry for camelCase but I'm addicted to it.


回答1:


I made it work by:

  • for the dealer, sending your message in multipart, the first part being an empty message, the second part being your message
  • reduced the timer (that one didn't help though)

Here is the code:

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()


来源:https://stackoverflow.com/questions/12915982/multithreading-and-zmq-dealer-rep-hello-world-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!