[zeromq-dev] Thread Safe sockets
Martin Lucina
martin at lucina.net
Tue Feb 7 02:16:39 CET 2012
On Mon, 6 Feb 2012 16:39:51 -0800
Nadav Samet <thesamet at gmail.com> wrote:
> >
> >
> > Can you elaborate on why such a socket would have to be stored as
> > ThreadLocal? Given that in ZeroMQ a single listening (bound/connected)
> > socket can have many other sockets connected to it, if threads A, B, C
> > want to talk to thread D then A, B, C each have their own socket
> > and all connect to D's inproc:// endpoint.
>
>
> One use case is when you write a library on top of zeromq that runs user
> code (maybe in form of callbacks) on threads A, B and C. Those callbacks
> needs a way to obtain a socket connected to D in order to reply. It could
> be passed to them as an argument, and they can pass that socket again to
> each function that they are calling, making the API more explicit than what
> you'd like. So you want to make it a bit easier on your users by having
> your library figuring out the right socket to use from the identity of the
> currently running thread.
1) IMHO callbacks are evil and in 90% of cases should be
eradicated :-) Of course if you've got a huge legacy code base then
you're stuck with 'em, so it's a valid use case.
2) The way I did this in a Python project was have each thread generate
a well-known inproc://enpoint based on id(self).
I guess you could make a general solution by having a TLS "own_socket",
but that only helps for referring to the socket from inside the thread
that owns it. Anyone external (or any other thread) trying to connect
to it still needs to somehow determine the correct inproc:// endpoint,
either by using some well-known generation scheme, or interrogating the
target thread.
--
Martin Lucina <martin at lucina.net>
More information about the zeromq-dev
mailing list