One ZeroMQ socket per thread or per call?

前端 未结 4 488
名媛妹妹
名媛妹妹 2021-01-06 16:32

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

4条回答
  •  情话喂你
    2021-01-06 17:00

    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).

提交回复
热议问题