Majid Azimi
Majid Azimi

Reputation: 5745

sleep before closing 0MQ sockets

In Code Connected book volume 1(page 23) there is a example for using PUSH, PULL messaging. Before closing sockets it uses sleep(). Here is the code:

printf("Total expected cost: %d msec\n", total_msec);
sleep(1); // Give 0MQ time to deliver

zmq_close(sink);
zmq_close(sender);
zmq_ctx_destroy(context);

What is that sleep(1) about? Is this general rule?

Upvotes: 2

Views: 182

Answers (2)

Pieter Hintjens
Pieter Hintjens

Reputation: 6669

The sleep (1) in taskvent.c and tasksink2.c were hangovers from when the examples still used 0MQ/2.2, and you can delete these two lines of code, if you're running on 0MQ/3.2. I've just done that, tested, and it works as you'd expect.

The reason: in 2.2, sockets were destroyed and messages discarded, when you terminated the context. In 3.2, messages will be delivered within a timeout specified by the LINGER socket option, which is by default infinite.

There are lots of other examples that use "sleep", for good reasons:

  • to simulate a workload
  • to let a set of peers in a demo start-up and connect
  • to let a set of peers in a demo shutdown
  • to retry after an error

You can do start-up and shutdown synchronization differently but it gets more complex than we want in simple examples.

Upvotes: 3

Flyer
Flyer

Reputation: 327

Using sleep(X) is a bad habit and denote usually a bad design. ZeroMQ is not famous for it's quality of implementation.

The intent here is to wait until ZeroMQ has sent all the pending messages present in the sending queue of the ZeroMQ socket.

1 second is assumed to be long enough but there is absolutely no guaranty. Thus the program will work most of the time but not all the time.

A better way would be to periodically retrieve the number of pending messages in the sending queue and wait until this number goes down to zero. An overall timeout could be added to avoid an infinite wait.

I don't know if ZeroMQ provide a such API.

Upvotes: -1

Related Questions