pebbe / zmq4

A Go interface to ZeroMQ version 4
BSD 2-Clause "Simplified" License
1.18k stars 163 forks source link

Add GetDefaultContext() call #79

Closed abligh closed 8 years ago

abligh commented 8 years ago

Signed-off-by: Alex Bligh alex@alex.org.uk

Add a GetDefaultContextCall() which returns the default context.

"Why do we need this?" you may well ask.

I am writing a package that is used in conjunction with pebbe/zmq4 (it presents ZMQ sockets as go channels). In order to function, it needs to create a number of PAIR sockets. These PAIR sockets need to be in the same context as the ZMQ socket passed to the the package to deal with, as they need to both be fed to a Poller. It is not possible (as far as I can see) to get the context from the socket. Therefore, the called needs to pass in the the context of the ZMQ socket so I can create other sockets in the same context. If the caller is using the default context, there is currently no way of the caller getting a pointer to the default context. With this call added, the caller can get the default context. Moreover the caller can pass nil as the context and my package can retrieve the default context.

An alternative route would be to store the context within the socket structure, but that is far more intrusive.

pebbe commented 8 years ago

If you know the socket is created in the default context, then you don't need the context to create new sockets in the same context.

The context of the socket is already there, in the field ctx. Why not add this:

func (soc *Socket) Context() (*Context, error) { 
    if !soc.opened {
        return nil, ErrorSocketClosed
    }
    return soc.ctx, nil
}

This always works, for default and non-default context.

(if the socket is closed, soc.ctx is nil)

abligh commented 8 years ago

A much better plan. I've updated the pull request to do exactly that.