- Workthread, which generally inherits Qthread, creates a temporary workobject in the overloaded run (), which determines whether the workobject is used in the thread
- So what if this workobject is a singleton?
Method 2: Use Workobject in Qthread
1. Create Workobject
1#include <QObject>2#include <QDebug>3#include <QThread>4 5 #defineDEBUG (x)6 {7Qdebug () <<"class Name:"<<x->metaobject ()->classname () <<"\ n"8<<"function:"<<__func__<<"\ n" 9<<"Thread id ="<<Qthread::currentthreadid ()Ten<<"\ n--------------------------------------------------"; One } A - classWorkobject: PublicQobject - { the Q_object - q_disable_copy (workobject) - - Public: + StaticWorkobject *getinstance () - { + StaticWorkobject instance; A return&instance; at } - - voidStart () {DEBUG ( This);} - - Private: - in ExplicitWorkobject (Qobject *parent =0) - : Qobject (parent) to {} +};
View Code
2. Create Workthread
1#include <QThread>2 3#include"workobject.h"4 5 classWorkthread: PublicQthread6 {7 Public:8Workthread (Qobject *parent =0)9 : Qthread (parent)Ten {} One A protected: - voidRun () - { theDEBUG ( This); -Workobject *pwork =workobject::getinstance (); -Pwork->start (); - } +};
View Code
3. Create Managerobject
1#include <QObject>2 3#include"workobject.h"4#include"workthread.h"5 6 classManagerobject: PublicQobject7 {8 Q_object9 Public:Ten ExplicitManagerobject (Qobject *parent =0) One : Qobject (parent) A {} - - voidStart () the { -DEBUG ( This); -Workobject *pobj =workobject::getinstance (); -Pobj->start (); + } - + voidThreadRun () A { atDEBUG ( This); -Workthread *pthread =NewWorkthread; -Pthread->start (); - } -};
View Code
4.main.cpp
1#include <QCoreApplication>2#include <QDebug>3 4#include"managerobject.h"5#include"workthread.h"6 7 8 intMainintargcChar*argv[])9 {Ten qcoreapplication A (argc, argv); One AQdebug () <<"main thread id ="<<qthread::currentthreadid () <<"\ n"; - Managerobject K; - K.start (); the K.threadrun (); - - //workthread *p = new Workthread; - //P->start (); + - returna.exec (); +}
View Code
5. Running Results
- So the application of Qt multithreading is also possible, of course, if the computational amount is not or feel this way more troublesome can use qt::concurrent. See Qt threads (3) qt::concurrent
QT Threading (2) using Workobject in Qthread