相关疑难解决方法(0)

如何在Qt,GCD风格的给定线程中执行仿函数或lambda?

在带有GCD的ObjC中,有一种在旋转事件循环的任何线程中执行lambda的方法.例如:

dispatch_sync(dispatch_get_main_queue(), ^{ /* do sth */ });
Run Code Online (Sandbox Code Playgroud)

要么:

dispatch_async(dispatch_get_main_queue(), ^{ /* do sth */ });
Run Code Online (Sandbox Code Playgroud)

[]{ /* do sth */ }在主线程的队列中执行某些操作(相当于在C++中),阻塞或异步.

我怎么能在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 …
Run Code Online (Sandbox Code Playgroud)

c++ qt multithreading

35
推荐指数
3
解决办法
2万
查看次数

标签 统计

c++ ×1

multithreading ×1

qt ×1