[zeromq-dev] Race condition in cppzmq zmq::socket_t::close() / cppzmq tag?

Eric Pederson ericacm at gmail.com
Thu Dec 15 08:39:54 CET 2016

Right - normally I would not access a socket from two threads.

The scenario is unit testing. We have a class that encapsulates a set of
sockets and also a thread with a loop that polls the sockets.

When the test is over, I do the following to clean it up:  close the
context so the poll blocked in the thread throws an exception with ETERM.
I close the sockets after catching the exception and returning from the
thread.  The destructor joins the thread so the object doesn't get
destroyed before the thread is finished.  Then the destructor continues and
the socket members get destroyed.  All this works fine normally because the
sockets are usually closed before the socket destructor runs.  But
sometimes the closing in the thread would race with the destruction.

I found that it is because some tests were not joining the thread but
instead detaching it.  So it looks like we have a nice deterministic
shutdown process finally.


That could only happen if the same socket was used or managed from multiple
> threads. As the documentation clearly states, sockets are intentionally not
> thread safe and must not be used from multiple threads.

-- Eric

On Wed, Dec 14, 2016 at 2:24 AM, Eric Pederson <ericacm at gmail.com> wrote:

> I ran into a race condition in zmq::socket_t::close() in cppzmq:
> *inline void *close() ZMQ_NOTHROW
> {
>     *if*(ptr == NULL)
> *// already closed        **return *;
> *// Someone can sneak in here and close the socket*
>     *int *rc = zmq_close (ptr);
>     ZMQ_ASSERT (rc == 0);
>     ptr = 0 ;
> }
> I worked around it using compare-and-swap to atomically check if it's
> already closed. Does that kind of fix sound reasonable for
> zmq::socket_t::close()?
> Also I wanted to follow up on my previous question about tagging cppzmq.
> I think that conversation got lost in the list shutdown that happened
> recently.  Does it make sense to regularly tag the cppzmq repo with the
> corresponding ZeroMQ version?
> Thanks,
> -- Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.zeromq.org/pipermail/zeromq-dev/attachments/20161215/65757a70/attachment.htm>

More information about the zeromq-dev mailing list