我可以在同一个ZeroMQ REQ/REP套接字上从一个线程发送()和从另一个线程发送recv()吗? [英] Can I send() from one thread and recv() from another on the same ZeroMQ REQ/REP Socket?

查看:303
本文介绍了我可以在同一个ZeroMQ REQ/REP套接字上从一个线程发送()和从另一个线程发送recv()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如文档所述,ZMQ套接字不是线程安全的 .因此,我认为标题的答案是否".

As the documents say, ZMQ sockets are not thread-safe. So I assume the answer to the title is 'No'.

不过,我仍然不知道如何实现无阻塞的请求-答复使用ZMQ的模式:

Still, I can't figure out how to implement a non-blocking request-reply pattern using ZMQ:

具体来说,客户端具有一个主线程,该线程继续处理来自(线程安全的)消息队列的业务处理消息.消息来自各种来源,例如网络,计时器,I/O等. 有时,主线程希望将请求发送到远程服务器,但是它不想等待响应(可能需要一段时间才能到达).

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. 主要消息处理循环线程.这将在REQ/REP套接字上send()请求
  2. 辅助侦听器线程,它将等待服务器的响应.这将在套接字上使用阻塞recv(),并将响应推送到主线程的队列.
  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.

我如何使用ZeroMQ做到这一点?辅助线程是否应该打开inproc套接字并侦听来自主线程的消息?

How would I achieve this using ZeroMQ? Should the auxilary thread open an inproc socket and listen to messages from the main thread?

推荐答案

实际上,单线程就足够了.只需将请求发送到服务器并使用zmq_poll()轮询消息即可.

Actually, single thread is enough. Just send request to the server and poll messages with zmq_poll().

如果一次请求足够,此模型很好.如果需要发送多个请求并异步读取答复,请使用DEALER套接字而不是REQ.只需发送一些requestId作为第一帧,然后添加空的定界符帧,然后发送实际请求即可.

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.

该指南的第3章提供了有关REQ/REP邮件信封的更多详细信息: http://zguide.zeromq .org/php:chapter3

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.

这篇关于我可以在同一个ZeroMQ REQ/REP套接字上从一个线程发送()和从另一个线程发送recv()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆