目录
参考博客
多线程可以使用的场景:如果有多个独立的功能,需要并行处理,此时为了提高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();
-
相关阅读:
TypeError: __init__() got an unexpected keyword argument ‘transport_options‘
某Android大厂面试100题,涵盖测试技术、环境搭建、人力资源......【速度领取】
更新Xcode 版本后运行项目出现错误 Unable to boot the Simulator 解决方法
Vue3项目引入 vue-quill 编辑器组件并封装使用
12.示例程序(定时器定时中断&定时器外部时钟)
Kubeadm搭建kubernetes(k8s)集群
进阶课2——语音分类
【Linux kernel/cpufreq】framework ----初识
HStreamDB v0.9 发布:分区模型扩展,支持与外部系统集成
JVM调优参数设置步骤
-
原文地址:https://blog.csdn.net/ljjjjjjjjjjj/article/details/127958689