Qt线程(2) QThread中使用WorkObject

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

  方式2:在QThread中使用WorkObject

  1.创建WorkObject

 #include <QObject>
 #include <QDebug>
 #include <QThread>

 #define DEBUG(x) \
 {\
     qDebug()<<"class name:"<<x->metaObject()->className()<<"\n"\
     <<"function:"<<__func__<<"\n" \
     <<"thread id = "<<QThread::currentThreadId()  \
     <<"\n--------------------------------------------------"; \
 }\

 class WorkObject : public QObject
 {
     Q_OBJECT

 public:
     static WorkObject *getInstance()
     {
           static WorkObject instance;
           return &instance;
     }

     void start(){DEBUG(this);}

 private:
     Q_DISABLE_COPY(WorkObject)
     )
         :QObject(parent)
     {}
 };

  2.创建WorkThread

 #include <QThread>

 #include "workobject.h"

 class WorkThread : public QThread
 {
 public:
     WorkThread(QObject *parent = )
         :QThread(parent)
     {}

 protected:
     void run()
     {
         DEBUG(this);
         WorkObject *pWork = WorkObject::getInstance();
         pWork->start();
     }
 };

  3.创建ManagerObject

 #include <QObject>

 #include "workobject.h"
 #include "workthread.h"

 class ManagerObject : public QObject
 {
     Q_OBJECT
 public:
     )
         :QObject(parent)
     {}

     void start()
     {
         DEBUG(this);
         WorkObject *pObj = WorkObject::getInstance();
         pObj->start();
     }

     void threadRun()
     {
         DEBUG(this);
         WorkThread *pThread =new  WorkThread;
         pThread->start();
     }
 };

  4.main.cpp

 #include <QCoreApplication>
 #include <QDebug>

 #include "managerobject.h"
 #include "workthread.h"

 int main(int argc, char *argv[])
 {
     QCoreApplication a(argc, argv);

     qDebug()<<"main thread id = "<<QThread::currentThreadId()<<"\n";
     ManagerObject k;
     k.start();
     k.threadRun();

     //WorkThread *p = new WorkThread;
    // p->start();

     return a.exec();
 }

  5.运行结果

  Qt线程(2) QThread中使用WorkObject

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