Can I send() from one thread and recv() from another on the same ZeroMQ REQ/REP Socket?

霸气de小男生 提交于 2019-12-12 19:03:04

问题


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:

  1. The main message-processing loop thread. This will send() request on the REQ/REP socket
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!