使用进程而不是使用zeromq的线程

时间:2015-04-29 16:35:58

标签: python multiprocessing zeromq

我正在阅读此代码http://zguide.zeromq.org/py:mtserver 但是,当我尝试将threading.Thread替换为multiprocessing.Process时,我收到了错误

  
    

断言失败:ok(mailbox.cpp:84)

  

代码是

import time
import threading
import zmq

def worker_routine(worker_url, context=None):
    """Worker routine"""
    context = context or zmq.Context.instance()
    # Socket to talk to dispatcher
    socket = context.socket(zmq.REP)

    socket.connect(worker_url)

    while True:

        string  = socket.recv()

        print("Received request: [ %s ]" % (string))

        # do some 'work'
        time.sleep(1)

        #send reply back to client
        socket.send(b"World")

def main():
    """Server routine"""

    url_worker = "inproc://workers"
    url_client = "tcp://*:5555"

    # Prepare our context and sockets
    context = zmq.Context.instance()

    # Socket to talk to clients
    clients = context.socket(zmq.ROUTER)
    clients.bind(url_client)

    # Socket to talk to workers
    workers = context.socket(zmq.DEALER)
    workers.bind(url_worker)

    # Launch pool of worker threads
    for i in range(5):
        process = multiprocessing.Process(target=worker_routine, args=(url_worker,))
        process.start()

    zmq.device(zmq.QUEUE, clients, workers)

    # We never get here but clean up anyhow
    clients.close()
    workers.close()
    context.term()

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:2)

每个传输的限制详见API

inproc用于进程内通信(即线程)。您应该尝试支持进程间通信的ipc,或者只是tcp