Skip to content

Commit

Permalink
Problem: shutdown() missing for context_t (zeromq#377)
Browse files Browse the repository at this point in the history
Solution: Add shutdown(). This function is required
for clean termination of the zmq context in multi-threaded
applications where sockets are used in threads. In particular
if blocking operation are used and if sockets can be created
at any time.

* Improve tests and documentation
  • Loading branch information
gummif authored and sigiesec committed Jan 27, 2020
1 parent 70d059b commit 47969cf
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
37 changes: 37 additions & 0 deletions tests/context.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,25 @@ TEST_CASE("context create, close and destroy", "[context]")
CHECK(NULL == (void *) context);
}

TEST_CASE("context shutdown", "[context]")
{
zmq::context_t context;
context.shutdown();
CHECK(NULL != (void *) context);
context.close();
CHECK(NULL == (void *) context);
}

TEST_CASE("context shutdown again", "[context]")
{
zmq::context_t context;
context.shutdown();
context.shutdown();
CHECK(NULL != (void *) context);
context.close();
CHECK(NULL == (void *) context);
}

#ifdef ZMQ_CPP11
TEST_CASE("context swap", "[context]")
{
Expand All @@ -26,4 +45,22 @@ TEST_CASE("context swap", "[context]")
using std::swap;
swap(context1, context2);
}

TEST_CASE("context - use socket after shutdown", "[context]")
{
zmq::context_t context;
zmq::socket_t sock(context, zmq::socket_type::rep);
context.shutdown();
try
{
sock.connect("inproc://test");
zmq::message_t msg;
sock.recv(msg, zmq::recv_flags::dontwait);
REQUIRE(false);
}
catch (const zmq::error_t& e)
{
REQUIRE(e.num() == ETERM);
}
}
#endif
12 changes: 12 additions & 0 deletions zmq.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,7 @@ class context_t

~context_t() ZMQ_NOTHROW { close(); }

// Terminates context (see also shutdown()).
void close() ZMQ_NOTHROW
{
if (ptr == ZMQ_NULLPTR)
Expand All @@ -691,6 +692,17 @@ class context_t
ptr = ZMQ_NULLPTR;
}

// Shutdown context in preparation for termination (close()).
// Causes all blocking socket operations and any further
// socket operations to return with ETERM.
void shutdown() ZMQ_NOTHROW
{
if (ptr == ZMQ_NULLPTR)
return;
int rc = zmq_ctx_shutdown(ptr);
ZMQ_ASSERT(rc == 0);
}

// Be careful with this, it's probably only useful for
// using the C api together with an existing C++ api.
// Normally you should never need to use this.
Expand Down

0 comments on commit 47969cf

Please sign in to comment.