0

I am new to ZeroMQ, I have seen a few examples, seems always involves the listener to do busy loop to receive the message, for example, in the pub/sub pattern. the receiver will need to do this to consume the message,

while (true)
{
    var message = socket.Recv(Encoding.UTF8);
    message.Dump();
}

Is there any kind of callback mechanism, like the receiver will just register itself to an socket, and whenever there is a message it will be called, instead of busy looping to check the message.

tesla1060
  • 2,621
  • 6
  • 31
  • 43
  • Its not busy-looping - `recv` blocks until a message is available. zmq sockets can only be used in a single thread so there is no place for the callback to come from without the thread calling down into the socket. If you are using a different library with callbacks, have your zmq thread queue the message there. – tdelaney May 18 '15 at 16:36

1 Answers1

0

Depends on your language choice. If, for example, you use node.js, everything is callbacks.

You don't specify your language choice, or what's going on in your application. Typically your strategy will depend on the overall nature of your application.

The reason you'll typically see a loop that is solely focused on receiving messages is twofold:

  1. These are examples, and that's the easiest way to write an example that will receive and deal with a message efficiently.
  2. ZMQ is a high volume toolset, typically when you're using it receiving messages is a high priority task for you, so dedicating an entire thread to receiving those messages might be a good idea.

That said, if you can define some larger loop in your application that you can receive messages once or only periodically during, you can just delegate the task to that larger loop. Say, something like (psuedocode):

while (functional_task) {
    while (msg = socket.recv()) {
        handle(msg);
    }
    do_other_stuff();
}

... that way you're processing all queued messages once per functional loop, rather than having a loop solely dedicated to your messages.

Whether or not you can use a callback system is largely dependent upon your language and ZMQ binding.

Jason
  • 13,606
  • 2
  • 29
  • 40
  • Per tdelaney's comment above, this answer assumes either using a ZMQ poller, or the ZMQ_NOBLOCK flag on your `recv()` call, which would cause the receive to not block and produce the scenario that OP is asking about above. – Jason May 18 '15 at 18:03