如何实现zmsg_recv_nowait?

时间:2013-02-14 08:00:39

标签: c zeromq

CZMQ库为nowaitzstr类(zframezstr_recv_nowait())提供zframe_recv_nowait()选项,但没有类似zmsg_recv_nowait()的内容。有什么解决方案吗?而不是zmq_msg_recv使用ZMQ_DONTWAIT标志。我的代码是:

zmq_pollitem_t items[] = { {sock, 0, ZMQ_POLLIN, 0} };
zmq_poll(items, 1, 10);
/* now receive all pending messages */
while (1) {
    zmsg_t *msg = zmsg_recv(sock); /* this will block after the last message received */
    /* consume message here */
}
/* sending bunch of messages */

我在做异步REQ/REP。发送多个请求然后在准备好后收到回复。此代码将阻止我的应用程序。另外我做一个zmq_poll,接收一条消息等等似乎很难看......因为在zmq_poll返回时,其他回复已经到了。

1 个答案:

答案 0 :(得分:2)

将轮询代码放入循环中。对一个套接字使用poll很好。

一个例子可能会有所帮助:

while (1) {
    /* now receive all pending messages */
    zmq_pollitem_t items[] = { {sock, 0, ZMQ_POLLIN, 0} };

    /* this will block for 10msec, ZMQ_POLL_MSEC is for compatibility for v2.2 */
    int rc = zmq_poll(items, 1, 10 * ZMQ_POLL_MSEC );
    if (rc == -1)
      break; // some error occured, check errno...

    if (items [0].revents & ZMQ_POLLIN) {
      /* there's something to receive */
      zmsg_t *msg = zmsg_recv(sock);
    }

    /* sending bunch of messages */
}