首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关闭来自其他线程的阻塞QLocalServer

关闭来自其他线程的阻塞QLocalServer
EN

Stack Overflow用户
提问于 2020-05-10 14:00:21
回答 1查看 173关注 0票数 0

我正在线程中运行一个阻塞的QLocalServer

代码语言:javascript
复制
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;
}

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

致以敬意,

EN

回答 1

Stack Overflow用户

发布于 2020-05-11 01:33:01

为什么不在设置m_abort之后,等到run()关闭或删除连接本身呢?

代码语言:javascript
复制
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变量。

从文档中:

此函数可用于使长时间运行的任务完全可中断。决不检查或操作此函数返回的值是安全的,但建议在长时间运行的函数中定期执行此操作。注意不要太频繁地调用它,以保持较低的开销。

所以你可以这样写:

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61707839

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档