0
\$\begingroup\$

I have a simple ZeroMQ client from zmqClient. I have refactored the code and done the following things.

  1. Created a class ZmqServer and added member variables and methods.

  2. Added a Server thread, using std::async

  3. Initialized a shared_ptr with ZmqServer and used std::move to pass that to the thread.

    #include <zmq.hpp>
    #include <iostream>
    #include <unistd.h>
    #include <future>
    #include <thread>
    
    class ZmqServer{
    public:
     ZmqServer() : m_context(1), m_socket(m_context, ZMQ_REP) {
     }
    
     void Bind(std::string protocol ,int port){
         std::string bind_param;
         bind_param = protocol + "://*:" + std::to_string(port);
         m_socket.bind(bind_param);
     }
    
     void receive(){
         zmq::message_t request;
         //  Wait for next request from client
         m_socket.recv (&request);
         std::cout << "Received message : " << request << std::endl;
     }
    
     void send(std::string msg){
         //  Send reply back to client
         zmq::message_t reply (msg.size());
         memcpy (reply.data (), msg.c_str(), 5);
         m_socket.send (reply);
     }
    
     private:
     zmq::context_t m_context;
     zmq::socket_t m_socket;
     };
    
     void server_thread(std::shared_ptr<ZmqServer> zmq){
    
      while (true) {
    
    
         zmq->receive();
         //  Do some 'work'
         sleep(1);
    
         //  Send reply back to client
         zmq->send("World");
     }
     }
    
    int main () {
    
       auto zmq = std::shared_ptr<ZmqServer>(new ZmqServer());
       zmq->Bind("tcp", 5555);
       auto f = std::async(std::launch::async, server_thread, std::move(zmq));
       while(true){
         std::cout << "Yay!!" << std::endl;
         f.get();
         std::this_thread::sleep_for(std::chrono::milliseconds(1000));
       }
       return 0;
    

    }

I want comments on the following

  1. overall refactoring of the code.
  2. The usage of std::async in this case? is it correct and appropriate
  3. usage of shared_ptr and std::move() in the context of thread.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.