[zeromq-dev] One socket per thread or per call?

Patrick Boettcher patrick.boettcher at posteo.de
Tue Jan 31 13:35:29 CET 2017

On Mon, 30 Jan 2017 23:22:57 +0100
Patrick Boettcher <patrick.boettcher at posteo.de> wrote:
> 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?

On SO I saw a related question where someone asked for a socketPool.
Seems not to exist in zmq - so I created one for my needs:

It is a thread-safe SocketPool "one-socket per thread":

  class socketPool
      std::string endpoint_;

      socketPool(const std::string &ep) : endpoint_(ep) {}

      zmq::socket_t & operator()()
          thread_local static zmq::socket_t socket(
          thread_local static bool connected;

          if (!connected) {
              connected = true;
          return socket;

  // creating a pool for a specific endpoint
  socketPool httpReqPool("ipc://http-concentrator");


  bool sendMessage(std::string s)
      zmq::socket_t &socket = httpReqPool();
      // the rest as before

The key here is the thread_local-storage from C++11.


More information about the zeromq-dev mailing list