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 };
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 };
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 };
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 }
5.运行结果
- 因此这样应用Qt的多线程也可以,当然如果计算量不大或则觉得这样的方式比较麻烦的可以使用Qt::Concurrent.见Qt线程(3) Qt::Concurrent
祝:玩得愉快!