为什么在从线程执行方法时使用QMetaObject :: invokeMethod [英] Why using QMetaObject::invokeMethod when executing method from thread

查看:1815
本文介绍了为什么在从线程执行方法时使用QMetaObject :: invokeMethod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

class A : public QObject
{
    Q_OBJECT
public:
    A() : QObject()
    {
         moveToThread(&t);
         t.start();
    }
    ~A()
    {
         t.quit();
         t.wait();
    }

    void doSomething()
    { 
         QMetaObject::invokeMethod(this,"doSomethingSlot");
    }
public slots:
    void doSomethingSlot()
    {
         //do something
         emit ready();
    }
signals:
    void ready();
private:
    QThread t;
}

问题为什么从 doSomething 它必须通过 QMetaObject :: invokeMethod 调用。我知道有连接类型的东西。

The question why from doSomething it must be call via QMetaObject::invokeMethod. I know that there is something with connection type. Could some one explain what is under the hood?

推荐答案

由于没有指定 Qt :: ConnectionType ,该方法将被调用 Qt :: AutoConnection ,这意味着它将被同步调用像正常的函数调用)如果对象的线程亲和力是对当前线程,否则异步。 异步意味着 QEvent 被构造并推送到消息队列中,并且将在事件循环到达时被处理。

As you haven't specified a Qt::ConnectionType, the method will be invoked as Qt::AutoConnection, which means that it will be invoked synchronously (like a normal function call) if the object's thread affinity is to the current thread, and asynchronously otherwise. "Asynchronously" means that a QEvent is constructed and pushed onto the message queue, and will be processed when the event loop reaches it.

使用 QMetaObject :: invokeMethod 如果收件人对象可能在另一个线程中的原因是试图直接在另一个线程中的对象上调用一个槽如果访问或修改非线程安全数据,则会导致损坏或更糟。

The reason to use QMetaObject::invokeMethod if the recipient object might be in another thread is that attempting to call a slot directly on an object in another thread can lead to corruption or worse if it accesses or modifies non-thread-safe data.

这篇关于为什么在从线程执行方法时使用QMetaObject :: invokeMethod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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