0

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;
}

如何从另一个线程关闭服务器?或者是使用非阻塞事件的唯一方法?

问候,

4

1 回答 1

0

为什么不等到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::requestInterruptionisInterruptionRequested()方法,而不是创建自己的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;
}
于 2020-05-10T17:33:01.063 回答