[zeromq-dev] Fwd: ZMQ Closure - Change of Beginners Documentation
mike at kaew.be
Wed May 25 11:40:56 CEST 2011
The following section of the starter guide for 0MQ newbies is misleading.
This is the section entitled 'Making a clean exit'
Currently this section promotes the idea of closing all sockets before
calling zmq_term. But for a multi threaded application with threads blocked
on zmq_recv, this will promote a solution where the user will be encouraged
to close the socket from the main thread of the program just prior to
calling zmq_term. 0MQ sockets are not thread safe and so instability will
I propose the guide is changed to the following -
Making a Clean Exit
Classy programmers share the same motto as classy hit men: always clean up
after yourself. When you use ØMQ in a language like Python, stuff gets
automatically freed for you. But when using C you must carefully free
objects when you're finished with them, or you get memory leaks, unstable
applications, and generally bad karma.
The ØMQ objects we need to worry about are messages, sockets, and contexts.
Luckily it's quite simple:
Always close a message the moment you are done with it, using
If you are opening and closing a lot of sockets, that's probably a sign
you need to redesign your application.
When you exit the program, close all the sockets _owned by the main
thread_ and then call zmq_term(). zmq_term() blocks and all sockets owned by
other application threads return ETERM -- either immediately, if they were
blocked in a zmq call, or when next zmq call is invoked -- you should
respond to ETERM by closing the socket. Once all sockets are closed
zmq_term() unblocks and application is free to terminate.
Calling zmq_term(3) <http://api.zeromq.org/2-1-3:zmq_term> while you have
open sockets will cause it to hang until all the sockets have closed. This
can be forever. Be sure that each thread closes the sockets that it opened.
Remember the sockets are not thread safe and so all commands working on a
specific socket should always be invoked from the same thread. Do not open a
socket in one thread, do a blocked receive to it in another and try to close
it from a third thread. Doing this will give you race conditions and
So by calling zmq_term your reader threads will release and they can then
close their sockets and exit. Because zmq_term is blocked until all the
sockets have closed, you will need to have first closed any sockets opened
by the execution thread that will be used to call the zmq_term. The thread
used for zmq_term is normally the main thread of the program but ultimately
is the one you used when you initialised the context (zmq_init).
Refer to the reference guide/man pages for more in depth explanations of
each command and to check which are thread safe.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the zeromq-dev