Qt线程(2) QThread中使用WorkObject

  • 一般继承QThread的WorkThread都会在重载的run()中创建临时的WorkObject,这样能确定这个WorkObject在该thread中使用
  • 那如果这个WorkObject是个Singleton是种什么情况呢?

  方式2:在QThread中使用WorkObject

  1.创建WorkObject

 1 #include <QObject>
 2 #include <QDebug>
 3 #include <QThread>
 4 
 5 #define DEBUG(x) \
 6 {\
 7     qDebug()<<"class name:"<<x->metaObject()->className()<<"\n"\
 8     <<"function:"<<__func__<<"\n" \
 9     <<"thread id = "<<QThread::currentThreadId()  \
10     <<"\n--------------------------------------------------"; \
11 }\
12 
13 class WorkObject : public QObject
14 {
15     Q_OBJECT
16 
17 public:
18     static WorkObject *getInstance()
19     {
20           static WorkObject instance;
21           return &instance;
22     }
23 
24     void start(){DEBUG(this);}
25 
26 private:
27     Q_DISABLE_COPY(WorkObject)
28     explicit WorkObject(QObject *parent = 0)
29         :QObject(parent)
30     {}
31 };
View Code

  2.创建WorkThread

 1 #include <QThread>
 2 
 3 #include "workobject.h"
 4 
 5 class WorkThread : public QThread
 6 {
 7 public:
 8     WorkThread(QObject *parent = 0)
 9         :QThread(parent)
10     {}
11 
12 protected:
13     void run()
14     {
15         DEBUG(this);
16         WorkObject *pWork = WorkObject::getInstance();
17         pWork->start();
18     }
19 };
View Code

  3.创建ManagerObject

 1 #include <QObject>
 2 
 3 #include "workobject.h"
 4 #include "workthread.h"
 5 
 6 class ManagerObject : public QObject
 7 {
 8     Q_OBJECT
 9 public:
10     explicit ManagerObject(QObject *parent = 0)
11         :QObject(parent)
12     {}
13 
14     void start()
15     {
16         DEBUG(this);
17         WorkObject *pObj = WorkObject::getInstance();
18         pObj->start();
19     }
20 
21     void threadRun()
22     {
23         DEBUG(this);
24         WorkThread *pThread =new  WorkThread;
25         pThread->start();
26     }
27 };
View Code

  4.main.cpp

 1 #include <QCoreApplication>
 2 #include <QDebug>
 3 
 4 #include "managerobject.h"
 5 #include "workthread.h"
 6 
 7 
 8 int main(int argc, char *argv[])
 9 {
10     QCoreApplication a(argc, argv);
11 
12     qDebug()<<"main thread id = "<<QThread::currentThreadId()<<"\n";
13     ManagerObject k;
14     k.start();
15     k.threadRun();
16 
17     //WorkThread *p = new WorkThread;
18    // p->start();
19 
20     return a.exec();
21 }
View Code

  5.运行结果

  

  • 因此这样应用Qt的多线程也可以,当然如果计算量不大或则觉得这样的方式比较麻烦的可以使用Qt::Concurrent.见Qt线程(3) Qt::Concurrent

  

转载于:https://www.cnblogs.com/hejianglin/p/5831500.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值