There are several ways to do this. The simplest approach might be to use REQ / REP sockets. Each background process / worker must have a REP socket, and you must use the REQ socket to communicate with them:
import zmq def worker(addr): context = zmq.Context() socket = context.socket(zmq.REP) socket.bind(addr) while True:
You will need to connect to each employee to send him a message and get the results:
context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect(worker_addr) socket.send('message') msg = socket.recv()
Another approach would be to use PUB / SUB to disable messages for workers and PUSH / PULL to get results:
import zmq def worker(worker_id, publisher_addr, results_addr): context = zmq.Context() sub = context.socket(zmq.SUB) sub.connect(publisher_addr) sub.setsockopt(zmq.SUBSCRIBE, worker_id) push = context.socket(zmq.PUSH) push.connect(results_addr) while True: msg = sub.recv_multipart()[1]
To pass a command to a specific employee, you should do something like:
context = zmq.Context() pub = context.socket(zmq.PUB) pub.bind(publisher_addr) # send message to worker-1 pub.send_multipart(['worker-1', 'hello'])
Pull the results:
context = zmq.Context() pull = context.socket(zmq.PULL) pull.bind(results_addr) while True: worker_id, result = pull.recv_multipart() print worker_id, result
source share