无事件循环或非 GUI / Qt 线程中使用 QTimer

【写在前面】

        Qt 中的 QTimer 相当简单、强大。

        然而,最近在脱离了 Qt 线程使用 QTimer 时遇上了不少问题。

        仔细阅读文档,发现到自己未注意到的细节 ( 我好蠢 T T. ),即需要事件循环:

In multithreaded applications, you can use QTimer in any thread that has an event loop. 

在多线程应用程序中,您可以在任何具有事件循环的线程中使用 QTimer。

         另一方面,QEventLoop ( Qt 事件循环 ) 最低依赖于 QCoreApplication ( 或 QGuiApplication / QApplication)。

        因此,想要在无事件循环或非 GUI / Qt 线程中使用 QTimer,有两种方法:

        1、既然需要事件循环,我们自己创建一个即可:使用本地 QEventLoop

        2、使用具有事件循环的 Qt 线程:QThread 即可。


【正文开始】

  • 首先,我们有一个非 Qt 线程,这里是 C++11 thread
std::thread thread([]{
    qDebug() << "std::thread id =" << QThread::currentThreadId();
    QTimer timer;
    timer.setInterval(1000);
    QObject::connect(&timer, &QTimer::timeout, []{
        qDebug() << "std::thread 1000 ms time out";
    });
    QEventLoop eventLoop;
    timer.start();
    eventLoop.exec();
});

        如果要在其中使用 QTimer,必须使其具有事件循环,因此需要手动创建一个 QEventLoop

        现在这个 std::thread 也具有事件循环了,你可以手动控制何时结束。

        但是,如果进一步封装,那不就是 QThread 了吗,又何必多此一举。

        实际上很多时候,非 Qt 线程并非指此处简单的示例,更多的是三方库 / 模块

        此时,当他们提供的回调 ( 等等 ) 位于线程中时,这种方式才能派上用场。

  • 如果换一种思路,我们可以实现一个 统一管理的 QTimer 集合,然后他们位于一个具有事件循环的线程即 QThread 中:
class TimerTask
{
public:
    TimerTask()
    {
        m_thread.start();
    }

    ~TimerTask()
    {
        for (auto &timer: m_timers) {
            if (timer->isActive()) timer->stop();
            timer->deleteLater();
        }

        m_thread.quit();
        m_thread.wait();
    }

    template<typename Task>
    void addTask(int interval, bool repeat, Task task)
    {
        QTimer *timer = new QTimer;
        timer->moveToThread(&m_thread);
        timer->setInterval(interval);
        timer->setSingleShot(!repeat);
        QObject::connect(timer, &QTimer::timeout, task);

        if (!repeat)
            QObject::connect(timer, &QTimer::timeout, timer, &QTimer::deleteLater);
        else
            m_timers.append(timer);

        QMetaObject::invokeMethod(timer, "start");
    }

private:
    QThread m_thread;
    QList<QTimer *> m_timers;
};

        关键的 addTask 通过 QObject::moveToThread() 将创建的 QTimer 移动到内部 QThread 即可,然后其他部分就是一些小细节的处理了( 此时 QTimer 已经在其他线程了,保险起见所以使用了 QMetaObject::invokeMethod,直接调用应该也没事 )。

        接下来使用看看效果 ( 方法一方法二一起了,应该不影响Ծ‸ Ծ ):

         然后是全部代码 ( 已经尽量简洁了 ):

#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QThread>

#include <thread>

class TimerTask
{
public:
    TimerTask()
    {
        m_thread.start();
    }

    ~TimerTask()
    {
        for (auto &timer: m_timers) {
            if (timer->isActive()) timer->stop();
            timer->deleteLater();
        }

        m_thread.quit();
        m_thread.wait();
    }

    template<typename Task>
    void addTask(Task task, int interval, bool repeat = true)
    {
        QTimer *timer = new QTimer;
        timer->moveToThread(&m_thread);
        timer->setInterval(interval);
        timer->setSingleShot(!repeat);
        QObject::connect(timer, &QTimer::timeout, task);

        if (!repeat)
            QObject::connect(timer, &QTimer::timeout, timer, &QTimer::deleteLater);
        else
            m_timers.append(timer);

        QMetaObject::invokeMethod(timer, "start");
    }

private:
    QThread m_thread;
    QList<QTimer *> m_timers;
};

void printCurrentThreadId() {
    qDebug() << "TimerTask thread id =" << QThread::currentThreadId();
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    std::thread thread([]{
        qDebug() << "std::thread id =" << QThread::currentThreadId();
        QTimer timer;
        timer.setInterval(1000);
        QObject::connect(&timer, &QTimer::timeout, []{
            qDebug() << "std::thread 1000 ms time out";
        });
        QEventLoop eventLoop;
        timer.start();
        eventLoop.exec();
    });

    TimerTask tasks;
    tasks.addTask([]{ qDebug() << "1000 ms time out"; }, 1000, true);
    tasks.addTask([]{ qDebug() << "2000 ms time out"; }, 2000, true);
    tasks.addTask(&printCurrentThreadId, 0, false);

    qDebug() << "main app thread id =" << QThread::currentThreadId();

    while (true) {
        QThread::msleep(1000);
    }
}

【结语】

        时隔四个月,其实每次写文章都很麻烦,而且为了保证正确,相关资料也看了不少,还要测试等等,是相当麻烦了。

        然后,我的计划里还有好多要写的 ( 因为学到了很多 ),会慢慢写的,所以记得关注呀 :-)。

        最后,代码放在 Github了:GitHub - mengps/QtExamples: 分享各种 Qt 示例,,说不定用得上呢~https://github.com/mengps/QtExamples

猜你喜欢

转载自blog.csdn.net/u011283226/article/details/117677228