Skip to content

Sharing ZContext between thread

Hasnain Bukhari edited this page Jul 30, 2018 · 5 revisions

As we might already know, zeromq Sockets are not thread-safe but zmq.Ctx is. So the thin wrapper ZMQ.Context is. Another wrapper ZContext is more convenient object which maintains created sockets. Unfortunately, it is not technically thread safe, because it keeps simple list of not thread-safe zeromq Sockets. Usual termination pattern on real world application is registering a control zeromq socket then send a message on it. On receiving the message, program can get out of a work loop. But in case of using proxy/device, there's no easy way to get out of the work loop in proxy/device. So we need to use shadowed ZContext

// in main thread
ZContext context = new ZContext();
ZContext shadowContext = ZContext.shadow(context);
new ProxyThread(shadowContext).run();
// wait termination request, ex Ctrl-C
context.destroy(); // sends context term message and waits all sockets closed by owning threads


// in proxy thread
Socket s1 = shadownContext.createSocket(...);
Socket s2 = shadownContext.createSocket(...);
ZMQ.proxy(s1, s2, ...);
// when parent context.destroy() is called, proxy is terminated 
shadownContext.destroy();

Or ZThread(https://github.com/zeromq/jeromq/blob/master/src/main/java/org/zeromq/ZThread.java) can create the shadow ZContext for you.

Clone this wiki locally