Qt core programming ___ QT thread

Source: Internet
Author: User

QtCore programmingQt threadIs the content to be introduced in this section,QtWe will introduce the core programming in several parts. For more information, see the editorial recommendations at the end for detailed reading. First, let's take a look at this article.

QtPairThreadProvides support, which introduces some basic platform-independentThreadClass,ThreadSecurity Event transfer method and globalQtThe library mutex allows youThreadCallQt.QtModerate andThreadThe application-related classes are shown in table 6.

Table 6QtModerate andThreadRelated Classes

UseThreadQt needs to provide support for the corresponding thread library. Therefore, the thread support option must be added when compiling and installing QT.

When compiling QT on Windows, thread support is an option on Some compilers. When compiling an application on a Windows operating system, you can solve this problem by adding an option in the qconfig. h file.

When compiling QT on Mac OS X and UNIX, you should add the-thread option when running the configure script. On UNIX platforms, multi-threaded programs must use special threads to support database connections, and multi-threaded programs 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 for compilation (for example, use-dqt_thread_support during compilation ).

1. Thread qthread

The qthread Thread class is provided in QT, which provides the method for creating a new thread. The thread starts execution by reloading 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 inherited from qthread and runs two threads. Thread B runs after thread a is run. The code is listed as follows:

  1. Class mythread: Public qthread {
  2. Public: Virtual void run ();
  3. };
  4. Void mythread: Run () // running thread {
  5. For (int count = 0;
  6. Count <20; count ++ ){
  7. Sleep (1 );
  8. Qdebug ("Ping! ");
  9. }
  10. }
  11. Int main (){
  12. Mythread;
  13. Mythread B;
  14. A. Start (); // It is executed by calling the run () function.
  15. B. Start ();
  16. A. Wait ();
  17. B. Wait ();
  18. }

Only one thread class is not enough. For programs that support multiple threads, it is also necessary to protect two different threads from simultaneously accessing data. Therefore, QT provides the qmutex class, A thread can lock the mutex. When the mutex is locked, it will block other threads from accessing critical data until the thread releases the mutex. In this way, critical data can be accessed by only one thread at a time.

The QT library mutex (qapp-> lock () and qapp-> unlock () are the mutex used to access the qt gui resources. Calling a function without mutex in QT usually leads to unpredictable behavior. To call a GUI-related function of QT from another thread, the QT library mutex is required. In this case, all functions that access graphics or window system resources are related to the GUI. If the object is accessed by only one thread, no mutex is required for the container class, string, or input/output class.

2. Thread-safe event Transmission

In QT, a thread is always an event thread. The thread pulls events from the window system and distributes them to the window components. Static Method qthread: postevent ships events from the thread rather than from the event thread. The event thread is awakened and the event is distributed in the event thread like an event in a normal window system. For example, you can force a window part to be repainted from different threads. The method is as follows:

  1. Qwidgets * mywidget; qthread: postevent (mywidget, new qpaintevent (qrect (0, 0,100,100 )));

The code above will asynchronously make mywidget redraw A Square area of 100*100 in its area.

In addition, some mechanisms are required to wake up a thread in the waiting state under a given condition. The qwaitcondition class provides this function. The qwaitcondition condition that the thread waits for is met, and qwaitcondition indicates what happened and it is blocked until this happens. When a given event occurs, qwaitcondition will wake up all threads waiting for the event or wake up any selected thread. (This function is the same as the POSIX thread condition variable and is an implementation of Unix .)

Example 2: qwaitcondition Application

The function of the following example is: when you press the button, the program will wake up the worker thread, and the thread will display the working status on the button: waiting or working ). When a button is pressed, the worker thread is working, which does not affect the thread. When the run function loops to mycond. Wait () Again, the thread is blocked and waits. When the button is pressed again, the slotclicked () function is triggered to wake up 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 signals inherited by qpushbutton with slot slotclicked ()
  7. Connect (this, signal (clicked (), slot (slotclicked (); // call the START () method inherited from qthread to start thread execution
  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 () // overload the run function {
  14. While (true) {// lock the application mutex lock, and set the window title to indicate that we are waiting to start working
  15. Qapp-> lock ();
  16. Setcaption ("Waiting ");
  17. Qapp-> unlock (); // wait until we are notified that we can continue
  18. Mycond. Wait (); // if so, it indicates that we have been awakened by another thread.
  19. Qapp-> lock ();
  20. Setcaption ("working! "); // Set the title, indicating that the job is in progress
  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 worker as the main window of the application
  29. Worker. Show ();
  30. Return app.exe C ();
  31. }

WhenThreadPrecautions for programming:

(1) do not perform any blocking operations when holding the QT library mutex. This will freeze the event loop.

(2) Make sure that the number of times you lock a recursive qmutex is equal to the number of times you unlock it.

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

(4) Beware of implicit shared classes. If you needThreadYou should use detach () to separate them.

(5) Be careful not to be designedThreadSecure QT class. For example, the qptrlist API is notThreadSecure, andThreadYou need to traverse a qptrlist, which should be locked before calling qptrlist: First () and unlocked after the end.

(6) Make sure that onlyThreadCreate objects inherited from qwidget, qtimer, and qsocketnotifier. On Some platformsThreadMedium, not GuiThreadThe object will never receive events in the underlying window system.

(7) similar to above, qnetwork class is used only in Gui thread. Because all qnetwork classes are asynchronous, there is no need to use qsocket in multithreading.

(8) Never tryThreadOfThreadTo call the processevents () function. This also includes qdialog: exec (), qpopupmenu: exec (), qapplication: processevents (), and other functions.

(9) In your application, do not setQtLibrary and supportThreadOfQtLibrary mixed use. This means that if your program uses supportThreadOfQtLibrary, you cannot connect to a commonQtLibrary and Dynamic LoadingQtLibrary or dynamically connect to other dependent normalQtLibrary or plug-in. In some systems, this will causeQtThe static data used in the database crashes.

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.