问题
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