[zeromq-dev] do I need to create a context more then once?

Justin Karneges justin at affinix.com
Mon Mar 4 02:37:32 CET 2013

On Monday, March 04, 2013 12:19:55 AM Peter Kleiweg wrote:
> I am writing a bindings library for ZeroMQ. I am thinking of
> hiding the creation and destroying of the context from the user.
> It would just create one context at start up of the program, use
> it for all sockets, and never destroy the context.
> What would be a reason to destroy the context?
> What would be a reason to open a second context?

The reason contexts exist in libzmq is so that multiple libraries using libzmq 
within the same app don't step on each other's initialization. If you've ever 
tried to use a library with global state across libraries you know how 
annoying this would be otherwise. As a user of libzmq, though, you should not 
create multiple contexts. The facility exists only so that the code of many 
single-context users can coexist.

Now, if you are designing a library of your own, it is probably a good idea to 
follow libzmq's model of not having a global state and instead require each 
user of your library to instantiate some kind of state/context/handle/etc in 
order to use it. In that case, each instantiation of your library could have 
its own libzmq context. How you decide this encapsulation is up to you, but in 
any case your library wouldn't be intentionally making multiple contexts of 
its own.

For my qzmq binding, zmq contexts are directly exposed as an object. As a 
convenience, socket objects may be created without specifying a parent 
context, and in this case a global shared context is used. The global context 
is reference counted, and destroyed when the last socket is destroyed. This 
convenience is acceptable for applications, but libraries using qzmq should 
always create their own contexts.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.zeromq.org/pipermail/zeromq-dev/attachments/20130303/5ad971eb/attachment.htm>

More information about the zeromq-dev mailing list