1

ZeroMQ is offering a zero-copy technique, where networking copying data is avoided as much as possible. However it doesn't seem to work (as tested with ZeroMQ v4.1.5).

This is the server code:

void CustomCleanup(void *data, void *hint)
{
  cout << "free1" << endl;
  delete static_cast<std::string*>(hint);
}

void my_free (void *data, void *hint)
{
    cout << "free2" << endl;
    free (data);
}

int main()
{
    //Allocate a string and zero copy it to client
    std::string* messageString = new string("ABCDEFG");
    cout << messageString->c_str() << endl;

    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_PUSH);
    socket.bind ("tcp://*:5555");

    zmq_msg_t msg;
    zmq_msg_init_data (&msg, messageString, messageString->length(), CustomCleanup, messageString);
    zmq_send (socket, &msg, 7, 0);

    cout << messageString->c_str() << endl;

    //Malloc a data buffer and zero copy it to client
    void *data = malloc (6);
    assert (data);
    memcpy (data, "ABCDEF", 6);
    zmq_msg_t msg2;
    int rc = zmq_msg_init_data (&msg2, data, 6, my_free, NULL); assert (rc == 0);

    zmq_send (socket, &msg2, 6, 0);
}

And this is the client code:

int main()
{
    zmq::context_t context (1);
    zmq::socket_t socket (context, ZMQ_PULL);
    socket.connect ("tcp://127.0.0.1:5555");

    zmq::message_t message;
    socket.recv(&message);
}

After the call to each zmq_msg_init_data, the deallocators CustomCleanup and my_free should be called to free the allocated memory but in my case this does not happen. Why?

Note: In the server example i used both new/malloc and both string and void pointers to help pinpoint a potential fault, but it is not working in either case.

charis
  • 429
  • 6
  • 16
  • did you try to manually close the socket and context after sending? I can imagine that ZMQ has no time to actually send the messages before your server terminates – king_nak Oct 13 '16 at 12:44
  • In the ZeroMQ c++ examples, the socket and context are never explicitly terminated. The same behavior happens even when the above code is inside a while(true) loop so i don't think is a timing issue – charis Oct 13 '16 at 13:01

0 Answers0