How to execute a functor or a lambda in a given thread in Qt, GCD-style?

后端 未结 5 1623
萌比男神i
萌比男神i 2020-11-22 05:11

In ObjC with GCD, there is a way of executing a lambda in any of the threads that spin an event loop. For example:

dispatch_sync(dispatch_get_main_queue(), ^         


        
5条回答
  •  没有蜡笔的小新
    2020-11-22 05:55

    May something like this be any useful?

    template 
    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));
    }
    

    This piece of code will make your lambda run on the main thread event loop as soon as it is possible. No args support, this is a very basic code.

    NOTE: I didn't test it properly.

提交回复
热议问题