QT Core programming qt thread (c)

Source: Internet
Author: User
Tags mutex

QT core programming qt thread is the content introduced in this sectionto,QT Core programming we want to be divided into several parts to introduce, want to refer to more content, please see the editor at the end of the recommendation for detailed reading, first look at this article.

QT provides support for threading , which introduces some basic platform-independent thread classes, how thread -Safe pass events, and global QT library mutexes allow you to get from different threads method of calling Qt . The classes in Qt that are related to threading applications are shown in table 6.

Table 6 thread -related classes in Qt

Using a thread requires QT to provide the appropriate line libraries support, so you need to add the Threading support option when you compile and install QT.

When QT is compiled on the Windows operating system, thread support is an option on some compilers. When compiling an application on the Windows operating system, this problem is resolved by adding an option to the Qconfig.h file.

When compiling QT on Mac OS X and UNIX, you should add the-thread option when you run the Configure script. On UNIX platforms, multithreaded threads must be connected with a special thread support library, and multithreaded threads must connect to the thread support library LIBQT-MT instead of the standard Qt library. When compiling an application, you should use the macro definition Qt_thread_support to compile (for example, use-dqt_thread_support at compile time).

1, Thread class Qthread

The Qthread thread class is provided in Qt, which provides a way to create a new thread. The thread is executed by overloading the Qthread::run () function, which is similar to the thread class in Java.

Example 1: A simple thread

The following example implements a simple user thread class that inherits from Qthread and runs 2 threads, and thread B runs after threads a runs out. The code is listed below:

  1. Class Mythread:public Qthread {
  2. public:virtual void Run ();
  3. };
  4. void Mythread::run ()//Run thread {
  5. for (int count = 0;
  6. Count < count++) {
  7. Sleep (1);
  8. Qdebug ("ping!");
  9. }
  10. }
  11. int main () {
  12. MyThread A;
  13. MyThread b;
  14. A.start (); By calling the run () function to execute the
  15. B.start ();
  16. A.wait ();
  17. B.wait ();
  18. }

Only one thread class is not enough, for multi-threaded programs, you also need to protect two different threads of data access, so Qt provides the Qmutex class, a thread can lock the mutex, when the mutex is locked, the other threads will block access to the critical data until the thread releases the mutex. In this way, the critical data can be protected only by one thread at a time.

The QT Library Mutex (Qapp->lock () and Qapp->unlock ()) is the amount of mutex used when accessing Qt's GUI interface resources. Calling a function without a mutex in QT often results in unpredictable behavior. A GUI-related function that calls QT from another thread requires the use of the QT library mutex. In this case, all functions that Access graphics or window system resources are related to the GUI. If the object is accessed only by one thread, no mutex is required to use the container class, string, or input/output classes.

2. Thread-Safe Event delivery

In Qt, a thread is always an event thread, and threads pull events out of the window system and distribute them to widgets. static method Qthread::p ostevent Mail The event from the thread, not from the event thread. The event thread is awakened and the event is distributed in the event thread just like an event of a normal window system. For example, you can force a window part to redraw from a different thread by doing the following:

    1. Qwidget *mywidget; Qthread::p ostevent (Mywidget, New Qpaintevent (qrect (0, 0, 100, 100));

The code above asynchronously causes Mywidget to redraw a square area of 100*100 in its area.

In addition, some mechanisms are needed to make the waiting thread wake up under a given condition. This functionality is provided by the Qwaitcondition class. The thread waits for the condition qwaitcondition satisfies, qwaitcondition indicates what happened and it blocks until this thing happens. When a given thing happens, Qwaitcondition will wake up all the threads waiting for the thing or wake up any of the selected threads. (This has the same functionality as POSIX thread condition variables and is an implementation on UNIX.) )

Example 2:qwaitcondition class application

The function of the following example is: When you press the button, the program wakes up the worker thread, which displays the working state on the button: Wait (Waiting) or work (working). When the button is pressed, the worker thread is working, and the thread does not have an impact. When the run function loops back to mycond.wait (), the thread blocks and waits. When the button is pressed again, the slotclicked () function is triggered to run, waking the waiting thread.

  1. #include <qapplication.h>
  2. #include <qpushbutton.h>//Global condition variable
  3. Qwaitcondition Mycond; Worker class implementation
  4. Class Worker:public Qpushbutton, public qthread{
  5. Q_object Public:worker (qwidget *parent = 0, const char *name = 0): Qpushbutton (parent, name) {
  6. SetText ("Start working"); Connect the signal inherited by the Qpushbutton to the slot slotclicked ().
  7. Connect (this, SIGNAL (clicked ()), SLOT (slotclicked ())); Invokes the start () method inherited from Qthread to begin the execution of the thread
  8. Qthread::start ();
  9. }
  10. Public slots:void slotclicked () {//Wake up a thread waiting for this condition variable
  11. Mycond.wakeone ();
  12. }
  13. Protected:void run ()//reload Run function {
  14. while (TRUE) {//locks the application mutex and sets the window caption to indicate that we are waiting to start working
  15. qapp->lock ();
  16. Setcaption ("Waiting");
  17. qapp->unlock (); Wait until we are told we can continue
  18. Mycond.wait (); If we get here, it means we've been woken up by another thread.
  19. qapp->lock ();
  20. Setcaption ("working!"); /Set the title to indicate that you are working
  21. qapp->unlock ();
  22. }
  23. }
  24. };
  25. int main (int argc, char **argv) {
  26. Qapplication app (argc, argv); Create a worker
  27. Worker Firstworker (0, "worker");
  28. App.setmainwidget (&worker); Set the worker as the main window of the application
  29. Worker.show ();
  30. return App.exec ();
  31. }

There are a few things to be aware of when threading programming:

(1) Do not do any blocking operations while holding the QT library mutex. This freezes the event loop.

(2) Confirm that you lock a recursive qmutex number of times equal to unlock the number of times, can not be more or less.

(3) Lock the QT application mutex before calling anything except the QT container and the tool class.

(4) Beware of hidden shared classes, and if you need to specify them between threads , you should separate them with detach ().

(5) Be careful not to be designed as a thread -Safe QT class, for example, Qptrlist API interface is not thread -safe, and if different threads need to traverse a qptrlist, They should be locked before calling Qptrlist::first () and unlocked after they reach the end point.

(6) Be sure to create only objects in the GUI thread that inherit from Qwidget, Qtimer, and Qsocketnotifier. On some platforms, objects created in threads instead of GUI threads never receive events from the underlying windowing system.

(7) Similar to the above, the Qnetwork class is used only in GUI threads. Because all Qnetwork classes are asynchronous, there is no need to use qsocket in multiple threads.

(8) Never try to call the Processevents () function in a thread that is not a GUI thread . This also includes qdialog::exec (), Qpopupmenu::exec (), Qapplication::p rocessevents (), and some other functions.

(9) In your application, do not mix the normal QT Library with the support thread 's qt Library. This means that if your program uses a support thread -based QT Library, you can't connect to a normal QT Library, load a regular QT Library dynamically, or dynamically connect to other dependent QT Library or plug-in. On some systems, doing so causes the static data that is used in the Qt Library to crash.

Summary:QT core programming QT thread content is finished, I hope this section of the content with your help, if you need more information, please refer to the editorial recommendations.

QT Core programming qt thread (c)

Related Article

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.