问题
As the documents say, ZMQ sockets are not thread-safe. So I assume the answer to the title is 'No'.
Still, I can't figure out how to implement a non-blocking request-reply pattern using ZMQ:
Specifically, the client has a main thread which goes on about its business processing messages from a (thread-safe) message queue. The messages come from various sources, such as network, timers, I/O etc. Occasionally the main thread wishes to send a request to a remote server, but it does not want to wait for a response (which may take a while to arrive).
Normally, I would use two threads:
- The main message-processing loop thread. This will
send()
request on the REQ/REP socket - An auxiliary listener thread which will wait for the response from the server. This will use a blocking
recv()
on the socket, and push the responses to the main thread's queue.
How would I achieve this using ZeroMQ? Should the auxilary thread open an inproc
socket and listen to messages from the main thread?
回答1:
Actually, single thread is enough. Just send request to the server and poll messages with zmq_poll()
.
This model is fine if one request at a time is suffucient. If you need so send multiple requests and read replies asynchronously, use DEALER socket instead of REQ. Just send some requestId as the first frame, then add empty delimiter frame, then send actual request.
Chapter 3 of the guide has more details about REQ/REP message envelopes: http://zguide.zeromq.org/php:chapter3
Please let me know if this isn't clear enough, I will probably extend my answer with few code samples.
来源:https://stackoverflow.com/questions/17572759/can-i-send-from-one-thread-and-recv-from-another-on-the-same-zeromq-req-rep