QT Advanced Programming Tips (ii)-writing multithreaded and concurrent applications

Source: Internet
Author: User

Before you can learn QT multithreaded programming, it is necessary to familiarize yourself with the concept of event loops first. Let's look at the main function code of a single-threaded interface program:

int main (int argc, char* argv[]) {qapplication app (argc,  argv);  Constructs the main Window object and displays MainWindow W;  W.show (); Enter the event loop return App.exec ();}

After the program initialization is complete, the main thread enters the main () function to begin executing the application code. In general, we build the interface object on the main thread and then go into the event loop to handle messages such as control drawing, user input, system output, and so on. This is what we typically call an event-driven model.

The main thread assumes the heavy responsibility of user interaction, when running time-consuming code on the main thread, it will affect the user's normal operation. So we often move some time-consuming and laborious computations out of the main thread, opening up new threads to run.

Qthread is a class used for thread management in QT, when invoking the start () method of a Qthread object creates a new thread and executes its run () method. By default, run () calls the Exec () method to enter its own message loop. As shown in the following:

In the main thread, the worker thread is the execution of the event loop, and notice that the main thread contains THR, W, objs these Qobject objects (these objects are created on the main thread). The event loop of the main thread is responsible for detecting whether the objects have messages to be processed, or calling the object's slot method. You can use the Qobject::movetothread method to move an object to another thread, such as:

Class Worker:public Qobject {    q_object    ...} void SomeFunc () {   qthread thr = new Qthread;   Worker worker = new worker;   Worker->movetothread (THR);   Thr->start ();
...}

If SomeFunc () is called on the main thread, then workerthread and the worker are associated on the main thread after creation, and when Worker->movetothread () is called, the Worker object is associated with the new thread:

Suppose we declare a workssignal () message on the MainWindow, declare and define a slot for Handleworks () on the Worker object, and connect workssignal and Handleworks in the following ways:

1. Qt::autoconnection -(default) If the message object and the slot object are associated under the same thread, use Qt::D irectconnection Way; Like MainWindow and worker two objects that are associated in different threads, will take the qt::queuedconnection way.

2. QT::D irectconnection -The slot method of the slot object is called directly when the message is sent. Note that the slot method here is executed on the thread that sent the message, and if the slot method is non-thread-safe, there is a problem.

3. Qt::queuedconnection -The sending thread resumes execution after the message is sent, the thread associated with the slot object detects the message during the event loop and calls the appropriate slot method.

4. Qt::blockingqueuedconnection -After the main thread sends the workssignal message, it blocks until the worker thread detects the message and runs Worker->handleworks () after the recovery.

5. Qt::uniqueconnection -can be associated with the above 4 methods and (or operation), indicating that the connection is unique. Tip You cannot have the same connection (Message object and slot object, message and slot are the same) that appear.

In particular, we do not recommend that the Qthread object be movetothread to the thread it is running on. The reason is that Qthread is designed as a class for managing threads, and we shouldn't be managing worker threads on worker threads, right. I don't want to talk more about the technical details, because this series of posts is designed to share experience skills rather than translating some documents.

In the project, I have implemented the background process by inheriting the Qthread class, filling in the tasks that the thread needs to run by overriding the run () function. In my previous blog post, I quickly realized the functionality of thread communication by embedding Inthreadobject objects on Qthread subclasses, review QT Advanced programming Techniques (i)-writing efficient signal & slot communication codes. There is also the following trick to implement timer event handling on a worker thread:

void Workerthread::run () {Qtimer tmr;      Associate the Qobject object on this thread with connect (&TMR, &qtimer::timeout, [=] () {dosomething ();  }); Tmr.start (+);  500 ms timing exec ();          Enter event Loop}

About multi-thread programming talk about this, hope can play a starting effect. In the actual project, you can refer to the following document design for multithreaded or concurrent applications:

* qtconcurrent:http://doc.qt.io/qt-5/qtconcurrent.html

* Thread support in qt:http://doc.qt.io/qt-5/threads.html

This article links: http://www.cnblogs.com/wenris/p/4450643.html.

Wenris, contact: <[email protected]>

Farewell O (∩_∩) o

QT Advanced Programming Tips (ii)-writing multithreaded and concurrent applications

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.