Consider the example code below (I typed it up quickly as an example, if there are errors it doesn't matter - I'm interested in the theory).
bool shutDown = false; //global
int main()
{
CreateThread(NULL, 0, &MessengerLoop, NULL, 0, NULL);
//do other programmy stuff...
}
DWORD WINAPI MessengerLoop( LPVOID lpParam )
{
zmq::context_t context(1);
zmq::socket_t socket (context, ZMQ_SUB);
socket.connect("tcp://localhost:5556");
socket.setsockopt(ZMQ_SUBSCRIBE, "10001 ", 6);
while(!shutDown)
{
zmq_msg_t getMessage;
zmq_msg_init(&getMessage);
zmq_msg_recv (&getMessage, socket, 0); //This line will wait forever for a message
processMessage(getMessage);
}
}
A thread is created to wait for incoming messages and to handle them appropriately. The thread is looping until shutDown
is set to true.
In ZeroMQ the Guide specifically states what must be cleaned up, namely the messages, socket and context.
My issue is: Since recv
will wait forever for a message, blocking the thread, how can I shut down this thread safely if a message is never received?
ZMQ_DONTWAIT
flag inzmq_msg_recv
, and add a manualSleep
for a short time period? So use a more polling method? – Wakayamasocket
variable available for closing.MessengerLoop
must contain only endlessrecv
loop. – Berryzmq_msg_recv
call. But this is just my guess. Once this call fails, exit the loop and the whole thread. – Berry