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:
- Class Mythread:public Qthread {
- public:virtual void Run ();
- };
- void Mythread::run ()//Run thread {
- for (int count = 0;
- Count < count++) {
- Sleep (1);
- Qdebug ("ping!");
- }
- }
- int main () {
- MyThread A;
- MyThread b;
- A.start (); By calling the run () function to execute the
- B.start ();
- A.wait ();
- B.wait ();
- }
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:
- 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.
- #include <qapplication.h>
- #include <qpushbutton.h>//Global condition variable
- Qwaitcondition Mycond; Worker class implementation
- Class Worker:public Qpushbutton, public qthread{
- Q_object Public:worker (qwidget *parent = 0, const char *name = 0): Qpushbutton (parent, name) {
- SetText ("Start working"); Connect the signal inherited by the Qpushbutton to the slot slotclicked ().
- Connect (this, SIGNAL (clicked ()), SLOT (slotclicked ())); Invokes the start () method inherited from Qthread to begin the execution of the thread
- Qthread::start ();
- }
- Public slots:void slotclicked () {//Wake up a thread waiting for this condition variable
- Mycond.wakeone ();
- }
- Protected:void run ()//reload Run function {
- while (TRUE) {//locks the application mutex and sets the window caption to indicate that we are waiting to start working
- qapp->lock ();
- Setcaption ("Waiting");
- qapp->unlock (); Wait until we are told we can continue
- Mycond.wait (); If we get here, it means we've been woken up by another thread.
- qapp->lock ();
- Setcaption ("working!"); /Set the title to indicate that you are working
- qapp->unlock ();
- }
- }
- };
- int main (int argc, char **argv) {
- Qapplication app (argc, argv); Create a worker
- Worker Firstworker (0, "worker");
- App.setmainwidget (&worker); Set the worker as the main window of the application
- Worker.show ();
- return App.exec ();
- }
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)