[zeromq-dev] One socket per thread or per call?
Patrick Boettcher
patrick.boettcher at posteo.de
Mon Jan 30 23:22:57 CET 2017
Hi all,
I'm new to zmq and still discovering things and I'd like your feedback
on a design decision.
(I asked the same question on StackOverflow, before seeing that there
is a zmq-mailing list.
http://stackoverflow.com/questions/41941702/one-zeromq-socket-per-thread-or-per-call)
As we all know, a ZeroMQ socket shall not be shared between application
threads. Contexts however can.
I have a multi-threaded-application and I'd like to have each thread
exchange messages from time to time with a REP-socket (event, exceptions
and the like) depending what they are doing (they are doing
non-ZeroMQ-stuff).
To send messages to my REP-socket I use the following function
(half-C++ half-pseudo-code):
bool sendMessage(std::string s)
{
zmq::socket_t socket(globalContext(), ZMQ_REQ);
socket.connect(ETT::IPC::httpV1ConcentratorEndpoint);
zmq::message_t message(s.size());
memcpy(message.data(), s.data(), s.size());
if (!socket.send(message))
return false;
// poll on socket for POLLIN with timeout
socket.recv(&message);
// do something with message
return true;
}
This function is called from every thread when needed. It creates a
local socket, connects, sends the message, and receives a response.
At exit, the socket is disconnected and removed (at least I'm
assuming that it is closed).
This way, I don't need to bother to maintain a socket in each of my
threads. This comes at the cost of creating and connecting each time I
call this function.
I stressed this code and I don't see much difference between reusing
one socket and this reconnect-implementation. (I have 20k REP-REQ per
second, including json-decode/encode, in both cases)
Is there a more correct ZeroMQ-way of doing this?
best regards,
--
Patrick.
More information about the zeromq-dev
mailing list