Issue with Qt thread affinity and moveToThread

后端 未结 4 1867
长发绾君心
长发绾君心 2021-01-13 07:58

I\'m trying to use threads in Qt to delegate some work to a thread, but I can\'t get it to work. I have a class inheriting QMainWindow that have a member object that launch

4条回答
  •  萌比男神i
    2021-01-13 08:39

    You can also move it to your thread by doing it from the object's owner thread.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    template 
    inline void runOnThread(QThread *qThread, Func &&func)
    {
        QTimer *t = new QTimer();
        t->moveToThread(qThread);
        t->setSingleShot(true);
        QObject::connect(t, &QTimer::timeout, [=]()
        {
            func();
            t->deleteLater();
        });
        QMetaObject::invokeMethod(t, "start", Qt::QueuedConnection, Q_ARG(int, 0));
    }
    
    
    
    void moveToThread(QObject *ptr, QThread *targetThrd=QThread::currentThread())
    {
        std::mutex mt;
        std::condition_variable_any cv;
        runOnThread(ptr->thread(),[&]
        {
            ptr->setParent(NULL);
            ptr->moveToThread(targetThrd);
            cv.notify_one();
        });
        cv.wait(mt);
    }
    

    You just need to call

    moveToThread( m_poller, m_pollThread);
    

提交回复
热议问题