Send ZeroMQ messages without sleep ()

I have this code of sending ZeroMQ message in my C application

void *socket= zmq_socket (context, ZMQ_DEALER);
// ...
zmq_msg_t zmsg;
zmq_msg_init_size (&zmsg, msg_size);
memcpy(zmq_msg_data (&zmsg), content, msg_size);
zmq_msg_send (&zmsg, socket, 0);
zmq_msg_close(&zmsg); 
sleep (1);

      

which does work, but I don't like the fact that I have to call sleep (1) to clear the messages. If I leave it, no messages will go to the server. Is there another way to "flush" messages on the socket without causing sleep? I am using ZeroMQ v3.2.2.

Many thanks!

EDIT: This behavior seems to only happen in debug mode.

+3


source to share


2 answers


Always make sure you close the socket and terminate the context. zmq_term()

will not return until messages have been sent. You can set LINGER on a socket to give an upper bound on how long it will wait before discarding messages. The default behavior is to wait always.



void *socket= zmq_socket (context, ZMQ_DEALER);
// ...
zmq_msg_t zmsg;
zmq_msg_init_size (&zmsg, msg_size);
memcpy(zmq_msg_data (&zmsg), content, msg_size);
zmq_msg_send (&zmsg, socket, 0);
zmq_msg_close(&zmsg);
zmq_close(socket);
zmq_term(context); // this will block until the message is actually sent

      

+1


source


Try to set the socket option ZMQ_LINGER

to 0, then close the socket after closing msg.



zmq_setsockopt(socket, ZMQ_LINGER, 0, sizeof(int));
...
zmq_close(socket);

      

+1


source







All Articles