我正在线程中运行阻塞QLocalServer
:
void QThread::stopServer()
{
m_abort = true;
m_server.close(); // QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
}
void QThread::run()
{
m_server = new QLocalServer();
m_server->Listen("PipeName");
while (!m_abort)
{
if (m_server->waitForNewConnection())
{
// handle the connection
}
}
delete m_server;
}
如何从另一个线程关闭服务器?还是使用非阻塞事件的唯一方法?
问候,
在设置m_abort
之后,为什么不等到run()
关闭或删除连接本身?
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和isInterruption Requested((方法,而不是创建自己的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;
}