首页 > 代码库 > Qt线程(2) QThread中使用WorkObject

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 QObject14 {15     Q_OBJECT16     Q_DISABLE_COPY(WorkObject)17 18 public:19     static WorkObject *getInstance()20     {21           static WorkObject instance;22           return &instance;23     }24 25     void start(){DEBUG(this);}26 27 private:28 29     explicit WorkObject(QObject *parent = 0)30         :QObject(parent)31     {}32 };
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

  

Qt线程(2) QThread中使用WorkObject