目录
参考博客
多线程可以使用的场景:如果有多个独立的功能,需要并行处理,此时为了提高cpu利用率,从而节省时间,可以采用多线程去实现。原理是把一个串行执行的任务,改变为多个并行任务,减少cpu的等待时间,例如同时读取写多个文件,并处理文件中的数据。
qt下多线程有2种方案,一种是派生QThread类,另一种是派生QObject
thread1.h
- #ifndef THREAD1_H
- #define THREAD1_H
-
- #include
- #include
-
- class thread1:public QThread
- {
- public:
- thread1();
- void run();
- };
-
- #endif // THREAD1_H
thread1.cpp
- #include "thread1.h"
-
- thread1::thread1()
- {
-
- }
-
- void thread1::run()
- {
- qDebug()<<"开启线程1";
- int i=0;
- while(1)
- {
- QThread::sleep(1); //1秒输出一次
- qDebug()<<"线程1的值:"<
- }
- }
派生类必须用指针,使用如下:
- thread1 *t1=new thread1;
- t1->start();
三、派生QObject
此时使用QObject的方法moveToThread将普通类加入到一个线程种
thread1.h
- #ifndef THREAD1_H
- #define THREAD1_H
-
- #include
- #include
-
- class thread1:public QObject
- {
- public:
- thread1();
- void startThread(); //开始执行线程入口
- };
-
- #endif // THREAD1_H
thread1.cpp
- #include "thread1.h"
-
- thread1::thread1()
- {
-
- }
-
- void thread1::startThread()
- {
- int i=0;
- while(1)
- {
- QThread::sleep(1); //1s执行1次
- qDebug()<<"当前i="<
- }
- }
使用时需要实例化一个QThread,然后把自己创建的类移动到这个QThread里面,最后需要执行自己创建的类里的方法,让线程运行起来
- //此类其实不属于线程,通过moveToThread将其移入QThread
- thread1*t1=new thread1;
- QThread* Thread=new QThread;
- t1->moveToThread(Thread);
- //移入线程后,需执行要执行的函数,才能进入线程
- connect(Thread,&QThread::started,t1,&thread1::startThread);
- //界面关闭退出线程
- connect(this , SIGNAL(destroyed()), t , SLOT(quit()));
- Thread->start();
-
相关阅读:
PBI 背景全屏规律呈现水印
UPS负载箱的工作原理是什么?
每 日 练 习
深聊测开领域之:一文搞懂什么是敏捷测试,如何做敏捷测试,建议先收藏再学习。
百日刷题计划 ———— DAY1
实时即未来,大数据项目车联网之原始数据实时ELT流式任务流程总结【七】
hand_springboot
深度学习交通车辆流量分析 - 目标检测与跟踪 - python opencv 计算机竞赛
ICSFUZZ:操纵I/O、二进制代码重用以及插桩,来Fuzzing工业控制应用程序
C++----IO流(参考C++ primer)
-
原文地址:https://blog.csdn.net/ljjjjjjjjjjj/article/details/127958689