当前位置:网站首页>[QT] QT multithreading development qthread

[QT] QT multithreading development qthread

2022-07-05 06:25:00 iriczhao

One 、QThread Two ways to use

QThread yes Qt The core classes used to run code in different threads , It is QObject Subclasses of

​ About QThread How to use ,Qt Officials offer two ways :

(1-1) Method 1

​ Step one : To create a new thread that executes some code , Subclass QThread And re implement run()

​ Step two : Then create an instance of the subclass and call start() Running threads

The following code snippet :

class MyThread : public QThread {
    
private:
	void run() override {
    
	//  Code to run in a new thread 
	}
};

MyThread *thread = new MyThread;
thread->start(); //  call run() Start a new thread 
// ...
thread->wait(); //  Wait for the thread to complete 

Thread has priority , You can specify it as an optional parameter start(), Or use setPriority() change .
​ When from run() return ( After a while ) The thread will stop running , The specific length of time is related to the operating system .

QThread::isRunning() and QThread::isFinished() Provides information about thread execution , You can get the running state of the thread through these two member functions .

QThread Yes QThread::started() and QThread::finished() Two signals .

​ A thread can call QThread:sleep() Function temporarily stops execution . Usually this is an inappropriate method of use , But more event driven ( Or poll ) It's much better .

​ Through to QThread call wait() To wait for the thread execution to complete , The maximum number of milliseconds to wait for optional directional function delivery .

(1-2) Method 2

​ Second use QThread establish 、 Methods of managing threads : It is not derived in essence QThread 了 . Steps are as follows :
(1) establish QThread
(2) Use moveToThread() Add objects to QThread Managed threads .
The following code snippet :

auto thread = new QThread;

auto worker = new Worker;

connect(thread, &QThread::started, worker, &Worker::doWork);
connect(worker, &Worker::workDone, thread, &QThread::quit);

connect(thread, &QThread::finished, worker, &Worker::deleteLater);

worker->moveToThread(thread);
thread->start();

​ QThread The second way to use , Allows us to run code in other threads without subclassing QThread.

Two 、Qt Two strategies of thread running

​ There are two basic strategies for running code in threads : No event loop and With event loop

(1) No event loop

​ Derived class QThread And overloading QThread::run() Member functions . Create an instance and use QThread::start() Start a new thread .

class MyThread : public QThread {
    
private:
	void run() override {
    
		loadFilesFromDisk();
		doCalculations();
		saveResults();
	}
};
auto thread = new MyThread;
thread->start();

thread->wait();

(2) With event loop

​ When dealing with timers 、 The Internet 、 Queuing signal / Slot link and other problems , Event cycling is necessary .

​ Qt Support single thread event loop , As shown in the figure below :
 Insert picture description here

​ The local event loop of each thread is QObjects Delivery events , If there is no event loop , Objects that exist in the corresponding thread will not receive events .

​ By means of run() Call in QThread::exec() To start the thread's local event loop . The following code snippet :

class MyThread : public QThread {
    
private:
	void run() override {
    
    auto socket = new QTcpSocket;
    socket->connectToHost(...);

    exec(); //  Run the event loop 

	//  Perform some cleanup operations 
    }  
};

QThread::quit() or QThread::exit() Will exit the event loop . have access to QEventLoop Or call it manually QCoreApplication::processEvents().

​ notes :QThread::run() The default implementation of actually calls QThread: exec (). If overloaded QThread::run(), We have to call it manually QThread: exec ().

3、 ... and 、QThread Precautions for use of

​ The following four types of operations cannot be performed in a non main thread :

(1) Execute on GUI Control operation . Including but not limited to : Use any QWidget / Qt Quick / QPixmap API; Use QImage, QPainter etc. , Yes. ; Use OpenGL It may be possible : But call at run time QOpenGLContext: supportsThreadedOpenGL () Necessary inspection .

(2) Cannot call Application::exec().

(3) After destroying the corresponding QThread Before the object , Be sure to destroy all in the secondary thread QObject.【 This is very important 】.

(4) Don't block. GUI Threads .

​ How to ensure QObjects Destroyed ? as follows :

​ (1) stay QThread::run() Create... On the stack QObject.

​ (2) Put their QObject::deleteLater() The slot function is connected to QThread::finished() The signal .

​ (3) hold QObject Move out of the thread .

​ For example, the following code snippet :

class MyThread : public QThread {
    
private:
	void run() override {
    
		MyQObject obj1, obj2, obj3;

		QScopedPointer<OtherQObject> p;
		if (condition)
			p.reset(new OtherQObject);

		auto anotherObj = new AnotherQObject;
		connect(this, &QThread::finished,anotherObj, &QObject::deleteLater);

		auto yetAnother = new YetAnotherQObject;

        //  Before exiting the thread , Move the object into the main thread  
        yetAnother->moveToThread(qApp->thread());
        //  Notify the main thread about this object in some way , 
        //  So it can be deleted .
        //  From this line of code , Don't use or operate on this QObject! 
	}
};

Four 、 summary

Qt Under the development of multithreading , Use QThread It's more convenient . This article records the use of QThread Two methods of , as well as QThread Event delivery mode of thread running in , Also record about QThread Some do's and don 'ts .

原网站

版权声明
本文为[iriczhao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140611510915.html