为什么不等到run()
关闭或删除连接本身,然后m_abort
设置?
void QThread::stopServer()
{
m_abort = true; // shall be thread-safe (std::atomic<bool>, etc)
wait(); // It’s optional to use it here
}
void QThread::run()
{
m_server = new QLocalServer();
m_server->Listen("PipeName");
while (!m_abort)
{
if (m_server->waitForNewConnection())
{
/* Most likely you cannot handle the connection
which was closed in another place, therefore сlose (delete)
it after leaving here */
}
}
delete m_server;
}
请注意,您可以使用标准的QThread::requestInterruption和isInterruptionRequested()方法,而不是创建自己的m_abort
变量。
从文档:
此功能可用于使长时间运行的任务完全可中断。永远不要检查或操作此函数返回的值是安全的,但是建议在长时间运行的函数中定期这样做。注意不要经常调用它,以保持低开销。
所以你可以写:
void QThread::stopServer()
{
requestInterruption();
wait(); // It’s optional to use it here
}
void QThread::run()
{
m_server = new QLocalServer();
m_server->Listen("PipeName");
while (!isInterruptionRequested())
{
if (m_server->waitForNewConnection(100)) // 100 ms for not to call too often
{
/* Most likely you cannot handle the connection
which was closed in another place, therefore сlose (delete)
it after leaving here */
}
}
delete m_server;
}