As we all know, a ZeroMQ socket shall not be shared among application threads.context_t
instances however can.
I have a multi-threaded-application a
Here is my (current) solution, in C++11 you can assign object to a thread_local
-storage. Storing the socket_t
-instance static
and thread_local
in a function gives me the functionality I was looking for:
class socketPool
{
std::string endpoint_;
public:
socketPool(const std::string &ep) : endpoint_(ep) {}
zmq::socket_t & operator()()
{
thread_local static zmq::socket_t socket(
globalContext(),
ZMQ_REQ);
thread_local static bool connected;
if (!connected) {
connected = true;
socket.connect(endpoint_);
}
return socket;
}
};
// creating a pool for each endpoint
socketPool httpReqPool("ipc://http-concentrator");
In my sendMessage()
-function instead of creating and connecting I simply do
bool sendMessage(std::string s)
{
zmq::socket_t &socket = httpReqPool();
// the rest as above
}
Regarding performance, well, it's 7 times faster on my machine. (140k REQ/REP
per second).