多线程和ZMQ DEALER / REP hello world不起作用

时间:2012-10-16 13:38:55

标签: python zeromq pyzmq

首先我的代码(主要来自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,但我沉迷于它。

1 个答案:

答案 0 :(得分:2)

我通过以下方式工作:

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

以下是代码:

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