QThread :: quit()是否丢弃EventQueue中的所有事件? [英] Does QThread::quit() discard all events in EventQueue?

查看:256
本文介绍了QThread :: quit()是否丢弃EventQueue中的所有事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有main功能:

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    Worker w;
    QObject::connect(&w, SIGNAL(done()), &a, SLOT(quit()), Qt::QueuedConnection);
    w.start();

    int ret = a.exec();
    w.quit();
    w.wait();

    return ret;
}

Worker的定义:

class Worker : public QThread
{
    Q_OBJECT
public:
    Worker(QObject *parent=0);
protected:
    void run();
protected slots:
    void process_request();
private:
    int ttl;
    Messenger* messenger;
}

Worker::Worker(QObject * parent)
    :QThread(parent),
    ttl(5),
    messenger(new Messenger(this))
{
    moveToThread(this);
    connect(messenger, SIGNAL(new_message()), SLOT(process_request()), Qt::QueuedConnection);
}

void Worker::finish(){
  quit();
  messenger->disconnectFromNetwork();   
}

void Worker::run(){
  messenger->connectToNetwork("somewhere");
  exec();
  emit done();
}

void Worker::process_request(){
    net_message msg;
    messenger->recv(msg);

    // PROCESSING

    messenger->send(msg);

    BOOST_LOG_SEV(file_log, severity::notification) << "TTL = " << ttl;
    if (--ttl == 0) {
        finish();
    }
}

好吧,很抱歉您的长期展览.这个想法是使Messenger驻留在主线程中,并在有新消息发送给Worker时戳它,而Worker只保留一定数量的消息,然后它停止并关闭整个应用程序.

Well, sorry for the long exposition. The idea was that the Messenger lives in the main thread, and pokes the Worker when it has a new message for it, and the Worker lives only a certain amount of messages, after which it stops and shuts down entire application.

但是有一个问题:日志文件包含行TTL = -1TTL = -2,依此类推.它不应该,我能想到的唯一原因是quit()并没有完全结束事件循环:它允许在从exec()返回之前处理待处理的事件.是这样吗?如果为否",那么什么可能导致这种行为?

But there is a problem: the log file has lines TTL = -1, and TTL = -2, and such. It shouldn't, and the only reason I can think about is that quit() doesn't quite ends the event loop: it allows pending events to be processed before returning from exec(). Is it so? If "no", then what may cause such a behaviour?

推荐答案

首先.

第二,文档没有说退出被调用后事件循环中队列的状态是什么. exec()可能在事件队列为空之后返回,以确保完成所有异步清除(如果这是最重要的事件循环,则为这种情况).

Secondly documentation doesn't say what is the state of queue in event loop after exit was called. It is possible that exec() returns after event queue is empty to make sure that all asynchronous cleanups are done (in case if this it top most event loop, in this case it is).



我已经
检查了源代码.显然在每次检查事件循环之间调用 QEventLoop::processEvents 应该退出.因此,看起来exec()仅在队列为空时才返回.


edit:
I've checked source code. Apparently QEventLoop::processEvents is call between each check that event loop should exit. So it looks like exec() returns only when queue is empty.

这篇关于QThread :: quit()是否丢弃EventQueue中的所有事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆