在Qt的官方文档,大家知道有两种方式使用 QThread。
You can use worker objects by moving them to the thread using QObject::moveToThread().
Another way to make code run in a separate thread, is to subclass QThread and reimplement run().
---------------------
前面文章讲到了moveToThread的使用,这篇文章我们探索继承QThread的方法实现多线程。
借用官网的demo: http://doc.qt.io/qt-5/qthread.html#details
class WorkerThread : public QThread
{
Q_OBJECT
void run() override {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals:
void resultReady(const QString &s);
};
void MyObject::startWorkInAThread()
{
WorkerThread *workerThread = new WorkerThread(this);
connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
workerThread->start();
}
虽然说这种方式也实现了多线程,但是,只有run()函数是运行在另外的线程中。假如你用信号触发WorkerThread的槽函数,你会发现这些函数都是在实例化WorkerThread的线程中运行的。
所以如果你想槽函数也是在新线程中运行(需要信号去触发槽函数),那么就需要使用moveToThread的方式了。
另外,注意多线程同时对某个对象进行操作时,考虑到线程安全问题,可能需要使用 QMutex,避免产生脏数据。