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

后端 未结 5 1617
萌比男神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:34

    I have absolutely no idea what your talking about, but I'm going to try to answer it any way.

    Lets say your have a class with a slot fucntion

    class MyClass : public QObject
    {
        Q_OBJECT
    public:
        MyClass() {}
    
    public slots: 
        void MySlot() { qDebug() << "RAWR";
    };
    

    So no if you want to run this synchronously in the main thread you can call that function directly. In order to connect a signal you need to create an object and connect a signal to the slot.

    class MySignalClass : public QObject
    {
        Q_OBJECT
    public:
        MySignalClass() {}
    
        signalSomthign() { emit someAwesomeSignal; }
    
    public signals: 
        void someAwesomeSignal();
    };
    

    And somwhere in the main thread you do something like

    MyClass slotClass;
    MySignalClass signalClass;
    qobject::connect(&signalClass, SIGNAL(someAwesomeSignal), &slotClass(), SLOT(MySlot)));
    

    So now if something you can connect multiple signals to that slot object, but realisticly the code I provided won't run any different than a normal function call. You'll be able to see that with a stack trace. If you add the flag qobject::queuedConneciton to the connect then it will que the slot call in the event loop.

    You can easily thread a signal as well, but this will automatically be a queuedConnection

    MyClass slotClass;
    MySignalClass signalClass;
    QThread someThread;
    slotClass.moveToThread(&someThread);
    qobject::connect(&signalClass, SIGNAL(someAwesomeSignal), &slotClass(), SLOT(MySlot)));
    

    Now you'll have a threaded signal basically. If your signal is going to be threaded then all you have to do is switch to signalClass.moveToThread(&someThread), when the signal is emitted signalClass will be run in the main thread.

    If you don't want an object to be called, I'm not sure, lamdas might work. I've used them before but Ithink they still need to be wrapped up in a class.

    qobject::connect(&signalClass, &slotClass::MySlot, [=]() { /* whatever */ });
    

    Although I'm pretty sure with Qt5 you can even go as far as creating a slot in line within a connect. But once your using lambdas I have no idea how threads work with them. As far as I know you need an object to sit in a thread basically to force calling the slot from the main thread.

提交回复
热议问题