在带有GCD的ObjC中,有一种方法可以在旋转事件循环的任何线程中执行lambda。例如:
dispatch_sync(dispatch_get_main_queue(), ^{ /* do sth */ });或者:
dispatch_async(dispatch_get_main_queue(), ^{ /* do sth */ });它在主线程的队列中阻塞或异步地执行一些东西(相当于C++中的[]{ /* do sth */ } )。
我如何在Qt中做同样的事情?
根据我所读到的,我猜解决方案是以某种方式向主线程的某个对象发送一个信号。但是什么对象呢?只有QApplication::instance()?(这是此时主线程中唯一存在的对象。)什么信号?
从目前的答案和我目前的研究来看,似乎我真的需要一些虚拟对象坐在主线程中,并有一些插槽,它只是等待进入一些代码来执行。
因此,我决定将QApplication子类添加进来。我当前的代码,它不能工作(但也许你可以帮助我):
#include <QApplication>
#include <QThread>
#include <QMetaMethod>
#include <functional>
#include <assert.h>
class App : public QApplication
{
    Q_OBJECT
public:
    App();
signals:
public slots:
    void genericExec(std::function<void(void)> func) {
        func();
    }
private:
    // cache this
    QMetaMethod genericExec_method;
public:
    void invokeGenericExec(std::function<void(void)> func, Qt::ConnectionType connType) {
        if(!genericExec_method) {
            QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(std::function<void(void)>)");
            int methodIndex = this->metaObject()->indexOfSlot(normalizedSignature);
            assert(methodIndex >= 0);
            genericExec_method = this->metaObject()->method(methodIndex);
        }
        genericExec_method.invoke(this, connType, Q_ARG(std::function<void(void)>, func));
    }
};
static inline
void execInMainThread_sync(std::function<void(void)> func) {
    if(qApp->thread() == QThread::currentThread())
        func();
    else {
        ((App*) qApp)->invokeGenericExec(func, Qt::BlockingQueuedConnection);
    }
}
static inline
void execInMainThread_async(std::function<void(void)> func) {
    ((App*) qApp)->invokeGenericExec(func, Qt::QueuedConnection);
}发布于 2014-02-09 08:23:08
这当然是有可能的。任何解决方案都将集中在传递一个事件,该事件将函数器包装到驻留在所需线程中的消费者对象。我们将这个操作称为metacall posting。这些细节可以通过几种方式执行。
Qt 5.10及更高版本TL;DR
// invoke on the main thread
QMetaObject::invokeMethod(qApp, []{ ... });
// invoke on an object's thread
QMetaObject::invokeMethod(obj, []{ ... });
// invoke on a particular thread
QMetaObject::invokeMethod(QAbstractEventDispatcher::instance(thread),
                         []{ ... });用于函数器的TL;DR
// https://github.com/KubaO/stackoverflown/tree/master/questions/metacall-21646467
// Qt 5.10 & up - it's all done
template <typename F>
static void postToObject(F &&fun, QObject *obj = qApp) {
  QMetaObject::invokeMethod(obj, std::forward<F>(fun));
}
template <typename F>
static void postToThread(F && fun, QThread *thread = qApp->thread()) {
   auto *obj = QAbstractEventDispatcher::instance(thread);
   Q_ASSERT(obj);
   QMetaObject::invokeMethod(obj, std::forward<F>(fun));
}
// Qt 5/4 - preferred, has least allocations
namespace detail {
template <typename F>
struct FEvent : public QEvent {
   using Fun = typename std::decay<F>::type;
   Fun fun;
   FEvent(Fun && fun) : QEvent(QEvent::None), fun(std::move(fun)) {}
   FEvent(const Fun & fun) : QEvent(QEvent::None), fun(fun) {}
   ~FEvent() { fun(); }
}; }
template <typename F>
static void postToObject(F && fun, QObject * obj = qApp) {
   if (qobject_cast<QThread*>(obj))
      qWarning() << "posting a call to a thread object - consider using postToThread";
   QCoreApplication::postEvent(obj, new detail::FEvent<F>(std::forward<F>(fun)));
}
template <typename F>
static void postToThread(F && fun, QThread * thread = qApp->thread()) {
   QObject * obj = QAbstractEventDispatcher::instance(thread);
   Q_ASSERT(obj);
   QCoreApplication::postEvent(obj, new detail::FEvent<F>(std::forward<F>(fun)));
}// Qt 5 - alternative version
template <typename F>
static void postToObject2(F && fun, QObject * obj = qApp) {
   if (qobject_cast<QThread*>(obj))
      qWarning() << "posting a call to a thread object - consider using postToThread";
   QObject src;
   QObject::connect(&src, &QObject::destroyed, obj, std::forward<F>(fun),
                    Qt::QueuedConnection);
}
template <typename F>
static void postToThread2(F && fun, QThread * thread = qApp->thread()) {
   QObject * obj = QAbstractEventDispatcher::instance(thread);
   Q_ASSERT(obj);
   QObject src;
   QObject::connect(&src, &QObject::destroyed, obj, std::forward<F>(fun),
                    Qt::QueuedConnection);
}void test1() {
   QThread t;
   QObject o;
   o.moveToThread(&t);
   // Execute in given object's thread
   postToObject([&]{ o.setObjectName("hello"); }, &o);
   // or
   postToObject(std::bind(&QObject::setObjectName, &o, "hello"), &o);
   // Execute in given thread
   postToThread([]{ qDebug() << "hello from worker thread"; });
   // Execute in the main thread
   postToThread([]{ qDebug() << "hello from main thread"; });
}用于方法/插槽的TL;DR
// Qt 5/4
template <typename T, typename R>
static void postToObject(T * obj, R(T::* method)()) {
   struct Event : public QEvent {
      T * obj;
      R(T::* method)();
      Event(T * obj, R(T::*method)()):
         QEvent(QEvent::None), obj(obj), method(method) {}
      ~Event() { (obj->*method)(); }
   };
   if (qobject_cast<QThread*>(obj))
      qWarning() << "posting a call to a thread object - this may be a bug";
   QCoreApplication::postEvent(obj, new Event(obj, method));
}
void test2() {
   QThread t;
   struct MyObject : QObject { void method() {} } obj;
   obj.moveToThread(&t);
   // Execute in obj's thread
   postToObject(&obj, &MyObject::method);
}单发计时器怎么样?
上面所有的方法都是在没有事件循环的线程中工作的。由于使用了QTBUG-66458,QTimer::singleShot的便利使用也需要在源线程中使用一个事件循环。然后postToObject变得非常简单,您可以直接使用QTimer::singleShot,尽管它是一个笨拙的名称,对那些不熟悉这个习惯用法的人隐藏了意图。通过一个名为的函数来更好地指示意图的间接性是有意义的,即使你不需要类型检查:
template <typename F>
static void postToObject(F && fun, QObject * obj = qApp) {
   if (qobject_cast<QThread*>(obj))
      qWarning() << "posting a call to a thread object - consider using postToThread";
   QTimer::singleShot(0, obj, std::forward<F>(fun));
}通用代码
让我们用下面的通用代码来定义我们的问题。最简单的解决方案是将事件发送到应用程序对象(如果目标线程是主线程),或者发送到任何其他给定线程的事件分派器。由于事件分派器仅在输入QThread::run之后才会存在,因此我们通过从needsRunningThread返回true来指示线程运行的要求。
#ifndef HAS_FUNCTORCALLCONSUMER
namespace FunctorCallConsumer {
   bool needsRunningThread() { return true; }
   QObject * forThread(QThread * thread) {
      Q_ASSERT(thread);
      QObject * target = thread == qApp->thread()
            ? static_cast<QObject*>(qApp) : QAbstractEventDispatcher::instance(thread);
      Q_ASSERT_X(target, "postMetaCall", "the receiver thread must have an event loop");
      return target;
   }
}
#endif元调用发布函数,在其最简单的形式中,要求函数调用消费者为给定的线程提供对象,并实例化函数调用事件。事件的实现仍然在我们的前面,并且是各种实现之间的本质区别。
第二个重载获取函数器的右值引用,潜在地保存了函数器上的复制操作。如果延续包含复制成本较高的数据,这将非常有用。
#ifndef HAS_POSTMETACALL
void postMetaCall(QThread * thread, const std::function<void()> & fun) {
   auto receiver = FunctorCallConsumer::forThread(thread);
   QCoreApplication::postEvent(receiver, new FunctorCallEvent(fun, receiver));
}
void postMetaCall(QThread * thread, std::function<void()> && fun) {
   auto receiver = FunctorCallConsumer::forThread(thread);
   QCoreApplication::postEvent(receiver,
                               new FunctorCallEvent(std::move(fun), receiver));
}
#endif出于演示的目的,工作线程首先将元调用发送到主线程,然后根据QThread::run()启动事件循环,以侦听来自其他线程的可能的元调用。互斥锁用于允许线程用户以一种简单的方式等待线程启动,如果使用者的实现需要的话。这样的等待对于上面给出的默认事件消费者是必要的。
class Worker : public QThread {
   QMutex m_started;
   void run() {
      m_started.unlock();
      postMetaCall(qApp->thread(), []{
         qDebug() << "worker functor executes in thread" << QThread::currentThread();
      });
      QThread::run();
   }
public:
   Worker(QObject * parent = 0) : QThread(parent) { m_started.lock(); }
   ~Worker() { quit(); wait(); }
   void waitForStart() { m_started.lock(); m_started.unlock(); }
};最后,我们启动上面的工作线程,它将元调用发送到主(应用程序)线程,而应用程序线程将元调用发送到工作线程。
int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   a.thread()->setObjectName("main");
   Worker worker;
   worker.setObjectName("worker");
   qDebug() << "worker thread:" << &worker;
   qDebug() << "main thread:" << QThread::currentThread();
   if (FunctorCallConsumer::needsRunningThread()) {
      worker.start();
      worker.waitForStart();
   }
   postMetaCall(&worker, []{ qDebug() << "main functor executes in thread" << QThread::currentThread(); });
   if (!FunctorCallConsumer::needsRunningThread()) worker.start();
   QMetaObject::invokeMethod(&a, "quit", Qt::QueuedConnection);
   return a.exec();
}在所有实现中,输出将大致如下所示。函数器跨线程:在主线程中创建的函数器在辅助线程中执行,反之亦然。
worker thread: QThread(0x7fff5692fc20, name = "worker") 
main thread: QThread(0x7f86abc02f00, name = "main") 
main functor executes in thread QThread(0x7fff5692fc20, name = "worker") 
worker functor executes in thread QThread(0x7f86abc02f00, name = "main") 使用临时对象作为信号源的Qt 5解决方案
对于Qt5,最简单的方法是使用临时QObject作为信号源,并将函数器连接到它的destroyed(QObject*)信号。当postMetaCall返回时,signalSource将被析构,发出其destroyed信号,并将元调用发送到代理对象。
这可能是C++11风格中最简洁、最直接的实现。signalSource对象以C++11 RAII的方式使用,以避免其销毁带来的副作用。短语“副作用”在C++11的语义中有一个含义,不应该被解释为“不可靠”或“不受欢迎的”-它绝非如此。QObject与我们的合同是在其析构函数执行过程中的某个时候发出destroyed,我们非常欢迎使用这一事实。
#include <QtCore>
#include <functional>
namespace FunctorCallConsumer { QObject * forThread(QThread*); }
#define HAS_POSTMETACALL
void postMetaCall(QThread * thread, const std::function<void()> & fun) {
   QObject signalSource;
   QObject::connect(&signalSource, &QObject::destroyed,
                    FunctorCallConsumer::forThread(thread), [=](QObject*){ fun(); });
}
#ifdef __cpp_init_captures
void postMetaCall(QThread * thread, std::function<void()> && fun) {
   QObject signalSource;
   QObject::connect(&signalSource, &QObject::destroyed,
                    FunctorCallConsumer::forThread(thread), [fun(std::move(fun))](QObject*){ fun(); });
}
#endif
// Common Code follows here如果我们只打算发布到主线程,代码就变得几乎微不足道了:
void postToMainThread(const std::function<void()> & fun) {
  QObject signalSource;
  QObject::connect(&signalSource, &QObject::destroyed, qApp, [=](QObject*){
    fun();
  });
}
#ifdef __cpp_init_captures
void postToMainThread(std::function<void()> && fun) {
  QObject signalSource;
  QObject::connect(&signalSource, &QObject::destroyed, qApp, [fun(std::move(fun))](QObject*){
    fun();
  });
}
#endif使用QEvent析构函数的Qt 4/5解决方案
同样的方法也可以直接应用于QEvent。事件的虚拟析构函数可以调用函数器。事件在由使用者对象的线程的事件分派器传递后立即被删除,因此它们总是在正确的线程中执行。这在Qt 4/5中不会改变。
#include <QtCore>
#include <functional>
class FunctorCallEvent : public QEvent {
   std::function<void()> m_fun;
   QThread * m_thread;
public:
   FunctorCallEvent(const std::function<void()> & fun, QObject * receiver) :
      QEvent(QEvent::None), m_fun(fun), m_thread(receiver->thread()) {}
   FunctorCallEvent(std::function<void()> && fun, QObject * receiver) :
      QEvent(QEvent::None), m_fun(std::move(fun)), m_thread(receiver->thread()) { qDebug() << "move semantics"; }
   ~FunctorCallEvent() {
      if (QThread::currentThread() == m_thread)
         m_fun();
      else
         qWarning() << "Dropping a functor call destined for thread" << m_thread;
   }
};
// Common Code follows here只发布到主线程,事情就变得更简单了:
class FunctorCallEvent : public QEvent {
   std::function<void()> m_fun;
public:
   FunctorCallEvent(const std::function<void()> & fun) :
      QEvent(QEvent::None), m_fun(fun) {}
   FunctorCallEvent(std::function<void()> && fun, QObject * receiver) :
      QEvent(QEvent::None), m_fun(std::move(fun)) {}
   ~FunctorCallEvent() {
      m_fun();
   }
};
void postToMainThread(const std::function<void()> & fun) {
   QCoreApplication::postEvent(qApp, new FunctorCallEvent(fun);
}
void postToMainThread(std::function<void()> && fun) {
   QCoreApplication::postEvent(qApp, new FunctorCallEvent(std::move(fun)));
}使用私有QMetaCallEvent的Qt 5解决方案
函数器可以被包装在QMetaCallEvent的Qt5插槽对象有效负载中。函数器将由QObject::event调用,因此可以发送到目标线程中的任何对象。此解决方案使用Qt 5的私有实现细节。
#include <QtCore>
#include <private/qobject_p.h>
#include <functional>
class FunctorCallEvent : public QMetaCallEvent {
public:
   template <typename Functor>
   FunctorCallEvent(Functor && fun, QObject * receiver) :
      QMetaCallEvent(new QtPrivate::QFunctorSlotObject<Functor, 0, typename QtPrivate::List_Left<void, 0>::Value, void>
                     (std::forward<Functor>(fun)), receiver, 0, 0, 0, (void**)malloc(sizeof(void*))) {}
   // Metacalls with slot objects require an argument array for the return type, even if it's void.
};
// Common Code follows here使用自定义事件和消费者的Qt 4/5解决方案
我们重新实现对象的event()方法,并让它调用函数器。这需要在函数被发送到的每个线程中有一个显式的事件消费者对象。对象在其线程结束时被清除,或者对于主线程,当应用程序实例被析构时被清除。它在Qt4和Qt5上都有效。使用右值引用可以避免复制临时函数。
#include <QtCore>
#include <functional>
class FunctorCallEvent : public QEvent {
   std::function<void()> m_fun;
public:
   FunctorCallEvent(const std::function<void()> & fun, QObject *) :
      QEvent(QEvent::None), m_fun(fun) {}
   FunctorCallEvent(std::function<void()> && fun, QObject *) :
      QEvent(QEvent::None), m_fun(std::move(fun)) { qDebug() << "move semantics"; }
   void call() { m_fun(); }
};
#define HAS_FUNCTORCALLCONSUMER
class FunctorCallConsumer : public QObject {
   typedef QMap<QThread*, FunctorCallConsumer*> Map;
   static QObject * m_appThreadObject;
   static QMutex m_threadObjectMutex;
   static Map m_threadObjects;
   bool event(QEvent * ev) {
      if (!dynamic_cast<FunctorCallEvent*>(ev)) return QObject::event(ev);
      static_cast<FunctorCallEvent*>(ev)->call();
      return true;
   }
   FunctorCallConsumer() {}
   ~FunctorCallConsumer() {
      qDebug() << "consumer done for thread" << thread();
      Q_ASSERT(thread());
      QMutexLocker lock(&m_threadObjectMutex);
      m_threadObjects.remove(thread());
   }
   static void deleteAppThreadObject() {
      delete m_appThreadObject;
      m_appThreadObject = nullptr;
   }
public:
   static bool needsRunningThread() { return false; }
   static FunctorCallConsumer * forThread(QThread * thread) {
      QMutexLocker lock(&m_threadObjectMutex);
      Map map = m_threadObjects;
      lock.unlock();
      Map::const_iterator it = map.find(thread);
      if (it != map.end()) return *it;
      FunctorCallConsumer * consumer = new FunctorCallConsumer;
      consumer->moveToThread(thread);
      if (thread != qApp->thread())
         QObject::connect(thread, SIGNAL(finished()), consumer, SLOT(deleteLater()));
      lock.relock();
      it = m_threadObjects.find(thread);
      if (it == m_threadObjects.end()) {
         if (thread == qApp->thread()) {
            Q_ASSERT(! m_appThreadObject);
            m_appThreadObject = consumer;
            qAddPostRoutine(&deleteAppThreadObject);
         }
         m_threadObjects.insert(thread, consumer);
         return consumer;
      } else {
         delete consumer;
         return *it;
      }
   }
};
QObject * FunctorCallConsumer::m_appThreadObject = nullptr;
QMutex FunctorCallConsumer::m_threadObjectMutex;
FunctorCallConsumer::Map FunctorCallConsumer::m_threadObjects;
// Common Code follows here发布于 2014-06-07 16:18:49
这样的东西会有什么用处吗?
template <typename Func>
inline static void MyRunLater(Func func) {
    QTimer *t = new QTimer();
    t->moveToThread(qApp->thread());
    t->setSingleShot(true);
    QObject::connect(t, &QTimer::timeout, [=]() {
        func();
        t->deleteLater();
    });
    QMetaObject::invokeMethod(t, "start", Qt::QueuedConnection, Q_ARG(int, 0));
}这段代码将使您的lambda尽可能快地在主线程事件循环上运行。没有args支持,这是一个非常基本的代码。
注意:我没有正确地测试它。
发布于 2020-02-07 05:16:26
其他人则有令人兴奋的答案。这是我的建议。而不是像这样做:
QMetaObject::invokeMethod(socketManager,"newSocket",
                          Qt::QueuedConnection,
                          Q_ARG(QString, host),
                          Q_ARG(quint16, port.toUShort()),
                          Q_ARG(QString, username),
                          Q_ARG(QString, passhash)
                          );做一些这样更好的事情:
QMetaObject::invokeMethod(socketManager,[=](){
    socketManager->newSocket(host,port.toUShort(),username,passhash);
},Qt::QueuedConnection);https://stackoverflow.com/questions/21646467
复制相似问题