问题描述
请考虑下面的示例代码(我以一个例子快速键入它,如果有错误没关系 - 我对理论感兴趣)。
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);
}
}
创建一个线程来等待传入的邮件适当处理它们。线程正在循环,直到 shutDown
设置为true。
A thread is created to wait for incoming messages and to handle them appropriately. The thread is looping until shutDown
is set to true.
在ZeroMQ中,明确说明了什么必须清理,即消息,套接字和上下文。
In ZeroMQ the Guide specifically states what must be cleaned up, namely the messages, socket and context.
我的问题是:由于 recv
将永远等待消息,阻塞线程,如何安全关闭此线程if
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?
推荐答案
阻塞调用将以几种方式退出。首先,这取决于您的语言和绑定,中断(Ctrl-C,SIGINT,SIGTERM)将退出调用。你会得到回来(再次,取决于你的绑定)一个错误或一个空消息(libzmq返回EINTR错误)。
The blocking call will exit in a few ways. First, and this depends on your language and binding, an interrupt (Ctrl-C, SIGINT, SIGTERM) will exit the call. You'll get back (again, depending on your binding) an error or a null message (libzmq returns an EINTR error).
其次,如果你终止上下文另一个线程,阻塞调用也将退出(libzmq返回ETERM错误)。
Second, if you terminate the context in another thread, the blocking call will also exit (libzmq returns an ETERM error).
第三,你可以在套接字上设置超时,超时,如果没有数据。我们不经常这样做,但在某些情况下它可能是有用的。
Thirdly, you can set timeouts on the socket so it will return in any case after some timeout, if there's no data. We don't often do this but it can be useful in some cases.
最后,我们在实践中做的不是阻塞接收,而是使用zmq_poll来找出套接字有消息等待,然后从这些套接字接收。这是向外扩展以处理更多套接字。
Finally, what we do in practice is never do blocking receives but use zmq_poll to find out when sockets have messages waiting, then receive from those sockets. This is how you scale out to handling more sockets.
这篇关于当recv阻塞时,如何正确清理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!