Qt 原始碼分析之moveToThread
這一次,我們來看Qt中關于將一個QObject物件移動至一個執行緒的函式moveToThread
- Qt 原始碼分析之moveToThread
- Qt使用執行緒的基本方法
- 原始碼分析
- 一些執行緒和信號槽使用的心得
Qt使用執行緒的基本方法
首先,我們簡單的介紹一下在Qt中使用多執行緒的幾種方法:
- 重寫
QThread的run函式,將要在多執行緒執行的任務放到run函式里
/*mythread.h*/
#pragma once
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject* parent = nullptr);
~MyThread();
protected:
void run() override;
};
/*mythread.cpp*/
#include "mythread.h"
#include <QDebug>
MyThread::MyThread(QObject* parent)
: QThread(parent)
{}
MyThread::~MyThread()
{}
void MyThread::run()
{
/*
在這個函式里執行耗時操作
*/
for (auto a = 0; a < 10; a++) {
qDebug() << u8"執行緒";
QThread::sleep(1);
}
}
/*呼叫函式*/
auto m_thread = new MyThread();
// 呼叫start之后,就會去執行run里內容了
m_thread->start();
但是這種方法,不被Qt官方所推薦,Qt官方所推薦的是將物件移動至執行緒的方法moveToThread
- 創建一個QThread物件,將物件移動至一個執行緒中,用信號槽的方式來觸發該物件的槽函式,此時槽函式是在執行緒中執行的
/*mytask.h*/
#pragma once
#include <QObject>
class MyTask : public QObject
{
Q_OBJECT
public:
MyTask(QObject *parent = nullptr);
~MyTask();
public slots:
void slotMyTask();
};
/*mytask.cpp*/
#include "mytask.h"
#include <QThread>
#include <QDebug>
MyTask::MyTask(QObject *parent)
: QObject(parent)
{}
MyTask::~MyTask()
{}
void MyTask::slotMyTask()
{
/* 在這里執行耗時操作 */
for (auto a = 0; a < 10; a++) {
qDebug() << u8"當前執行緒: " << QThread::currentThread();
qDebug() << u8"執行緒";
QThread::sleep(1);
}
}
/*使用方法*/
// 1. 創建任務物件以及執行緒物件
auto m_task = new MyTask();
auto* m_thread = new QThread();
// 2. 將任務物件移動至執行緒
m_task->moveToThread(m_thread);
// 3. 將信號與任務類的槽連接起來
connect(m_thread, &QThread::started, m_task, &MyTask::slotMyTask);
// 4. 開啟執行緒
m_thread->start();

Note:
這里有一個坑,那就是如果一個QObject物件是有父物件的,那么該物件,就不能被移動至執行緒,測驗代碼如下:
// 1. 創建一個有父物件的任務物件以及執行緒物件
auto m_task = new MyTask(this);
auto* m_thread = new QThread();
// 2. 將任務物件移動至執行緒
m_task->moveToThread(m_thread);
// 3. 將信號與任務類的槽連接起來
connect(m_thread, &QThread::started, m_task, &MyTask::slotMyTask);
// 4. 開啟執行緒
m_thread->start();
此時,我們看到控制臺會輸出:
Cannot move objects with a parent (無法移動一個有父物件的object)

并且,我們能看到槽函式里列印的執行緒為主執行緒,
- 使用Qt的
QtConcurrent,缺點之一是沒有辦法手動退出
// 使用這個,需要在頭檔案里引入
#include <QtConcurrent/QtConcurrent>
// 定義一個任務函式
int MainWindow::taskTest(int a)
{
for (auto i = 1; i < 10; i++) {
qDebug() << "a: " << a;
QThread::sleep(1);
}
return 0;
}
/* 使用方法 */
// 在函式后面跟上你要設定給函式的引數
QtConcurrent::run(this, &MainWindow::taskTest, 10);
注意:在Qt里,子執行緒不能進行任何的ui更新操作,ui的更新操作全部只能在主執行緒
原始碼分析
然后,我們淺淺的分析一下,QObject中的moveToThread,主要分為三個部分
- 對一些基本條件的判斷:
-
移動的物件是否已經在目標執行緒
-
移動的物件是否有父物件(這就是我們上面說到的坑)
-
不能將一個視窗物件移動至其他執行緒,因為Qt要求所有UI操作都必須在主執行緒中執行,執行緒中如果想要更新UI,需要用信號槽來通知界面進行更改,
-
// 當前物件已經在目標執行緒了
if (d->threadData.loadRelaxed()->thread.loadAcquire() == targetThread) {
// object is already in this thread
return;
}
// 不能移動一個有父物件的物件
if (d->parent != nullptr) {
qWarning("QObject::moveToThread: Cannot move objects with a parent");
return;
}
// 視窗部件不能移動到一個新的執行緒,在Qt里GUI操作只能在主執行緒
if (d->isWidget) {
qWarning("QObject::moveToThread: Widgets cannot be moved to a new thread");
return;
}
- 對要移動的物件當前所屬執行緒的一些判斷:
-
如果要移動的物件沒有執行緒依附性,那么可以移動至目標執行緒
-
如果移動操作所在執行緒與移動物件所在執行緒不一致,那么不允許去移動
-
QThreadData *currentData = QThreadData::current();
QThreadData *targetData = targetThread ? QThreadData::get2(targetThread) : nullptr;
QThreadData *thisThreadData = d->threadData.loadRelaxed();
if (!thisThreadData->thread.loadAcquire() && currentData == targetData) {
// 如果一個物件沒有執行緒依附性,允許移動一個物件到一個執行緒
// one exception to the rule: we allow moving objects with no thread affinity to the current thread
currentData = d->threadData;
} else if (thisThreadData != currentData) {
// 不能在不是物件的執行緒里,去移動該物件至另外一個物件
qWarning("QObject::moveToThread: Current thread (%p) is not the object's thread (%p).\n"
"Cannot move to target thread (%p)\n",
currentData->thread.loadRelaxed(), thisThreadData->thread.loadRelaxed(), targetData ? targetData->thread.loadRelaxed() : nullptr);
#ifdef Q_OS_MAC
qWarning("You might be loading two sets of Qt binaries into the same process. "
"Check that all plugins are compiled against the right Qt binaries. Export "
"DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded.");
#endif
return;
}
- 正式的移動操作
// prepare to move
d->moveToThread_helper();
if (!targetData)
targetData = https://www.cnblogs.com/codegb/archive/2023/03/26/new QThreadData(0);
// make sure nobody adds/removes connections to this object while we're moving it
QMutexLocker l(signalSlotLock(this));
QOrderedMutexLocker locker(¤tData->postEventList.mutex,
&targetData->postEventList.mutex);
// keep currentData alive (since we've got it locked)
currentData->ref();
// move the object
d_func()->setThreadData_helper(currentData, targetData);
locker.unlock();
// now currentData can commit suicide if it wants to
currentData->deref();
一些執行緒和信號槽使用的心得
到了夾帶私活時間,下面是一些多執行緒使用信號槽的一點小心得總結
- 不能在子執行緒去更新UI界面,只能在主執行緒進行更新,
- 可以通過信號槽連接,在子執行緒通知主執行緒去更新UI
- 跨執行緒使用信號槽,建議用
QueuedConnection,因為這種連接方式,Qt會把信號丟到事件回圈里去,這樣槽函式會在接收者所在的執行緒執行,而DirectConnection這種連接方式,因為是直接回呼槽函式,槽會在信號發出的執行緒進行呼叫,具體可看上篇關于信號與槽原始碼分析, - 但是使用
QueuedConnection這種連接方式,信號的引數如果是自己定義的型別,一定要記得使用qRegisterMetaType來進行注冊,或者使用Q_DECLARE_METATYPE來進行注冊,否則,槽函式將不會觸發, BlockQueuedConnection這種方法慎用,因為如果信號發送者和接收者在同一個執行緒,將會導致死鎖,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/548198.html
標籤:其他
