关闭从其他线程阻止QLocalServer

时间:2020-05-10 06:00:21

标签: qt qthread qtcpsocket qlocalsocket qlocalserver

我正在线程中运行阻塞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;
}

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

此致

1 个答案:

答案 0 :(得分: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;
}