-
Notifications
You must be signed in to change notification settings - Fork 489
Sharing ZContext between thread
Dongmin Yu edited this page Jan 7, 2015
·
5 revisions
As we might already know, zeromq Sockets are not thread-safe but zmq.Ctx
is. So the thin wrapper ZMQ.Context
is. ZContext
is a bit 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 ZContxt();
ZContext shadowContext = ZContext.shadhow(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.destory() is called, proxy is terminated
shadownContext.destory();