Qt源码分析之moveToThread qt中move
liebian365 2024-10-17 14:00 27 浏览 0 评论
这一次,我们来看Qt中关于将一个QObject对象移动至一个线程的函数moveToThread
1、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的更新操作全部只能在主线程
QT开发交流+赀料君羊:714620761
2、源码分析
然后,我们浅浅的分析一下,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 = 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();
3、线程和信 号槽使用心得
下面是一些多线程使用信号槽的一点小心得总结
- 不能在子线程去更新UI界面,只能在主线程进行更新。
- 可以通过信号槽连接,在子线程通知主线程去更新UI
- 跨线程使用信号槽,建议用QueuedConnection,因为这种连接方式,Qt会把信号丢到事件循环里去,这样槽函数会在接收者所在的线程执行。而DirectConnection这种连接方式,因为是直接回调槽函数,槽会在信号发出的线程进行调用。具体可看上篇关于信号与槽源码分析。
- 但是使用QueuedConnection这种连接方式,信号的参数如果是自己定义的类型,一定要记得使用qRegisterMetaType来进行注册,或者使用Q_DECLARE_METATYPE来进行注册。否则,槽函数将不会触发。
- BlockQueuedConnection这种方法慎用,因为如果信号发送者和接收者在同一个线程,将会导致死锁。
相关推荐
- 4万多吨豪华游轮遇险 竟是因为这个原因……
-
(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...
- “菜鸟黑客”必用兵器之“渗透测试篇二”
-
"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...
- 科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白
-
作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...
- 麦子陪你做作业(二):KEGG通路数据库的正确打开姿势
-
作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...
- 知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势
-
智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...
- 每日新闻播报(September 14)_每日新闻播报英文
-
AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...
- 香港新巴城巴开放实时到站数据 供科技界研发使用
-
中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...
- 5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper
-
本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...
- Qt动画效果展示_qt显示图片
-
今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...
- 如何从0到1设计实现一门自己的脚本语言
-
作者:dong...
- 三年级语文上册 仿写句子 需要的直接下载打印吧
-
描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...
- C++|那些一看就很简洁、优雅、经典的小代码段
-
目录0等概率随机洗牌:1大小写转换2字符串复制...
- 二年级上册语文必考句子仿写,家长打印,孩子照着练
-
二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- wireshark怎么抓包 (75)
- qt sleep (64)
- cs1.6指令代码大全 (55)
- factory-method (60)
- sqlite3_bind_blob (52)
- hibernate update (63)
- c++ base64 (70)
- nc 命令 (52)
- wm_close (51)
- epollin (51)
- sqlca.sqlcode (57)
- lua ipairs (60)
- tv_usec (64)
- 命令行进入文件夹 (53)
- postgresql array (57)
- statfs函数 (57)
- .project文件 (54)
- lua require (56)
- for_each (67)
- c#工厂模式 (57)
- wxsqlite3 (66)
- dmesg -c (58)
- fopen参数 (53)
- tar -zxvf -c (55)
- 速递查询 (52)