(73 lessons) multithreaded programming in QT (i)

Source: Internet
Author: User
Tags sleep function thread class volatile

First, QT through the Qthread directly support multithreading

1, Qthread is a cross-platform multi-threaded solution

2, Qthread in a simple and easy-to-use way to achieve multithreaded programming


Note: 1. Threads in QT are created and used in the form of objects

2. Each thread corresponds to a Qthread object


Qthread This class, is a thread parent class, we need to inherit this qthread class.

The Qthread class, which provides a set of member functions. A thread is represented in the form of an object, so that we create a

Thread, it is actually creating an object of this Qthread thread class

One thread corresponds to a Qthread object


Ii. key member functions in Qthread

1. void Run ()

The thread body function, which defines the thread function (execution flow), is the entry function of the thread.

2. void Start ()

startup function, after a thread is actually created in the operating system, set the thread entry address to the Run function

3. void Terminate ()

Force end thread (not recommended)


Iii. Customizing a thread class

class mythread : public qthread{protected:    //protection, protected member functions, cannot be accessed directly by the outside world, However, the         void run () can be accessed directly by the Quilt class ()     // Override the run member function in the Qthread class to implement our thread-body logic         {             for  ( int i = 0; i < 5;  i++)             {                 qdebug ()  << objectName ()  <<i;    //objectname, the name of the current object                  sleep (1);     //This sleep function, is a static member function inside the Qthread class             }         }};int  main (int argc, char *argv[]) {    mythread t;    / /Create Child thread     t.setobjectname ("T"),     //set T object with the name t     t.start ();     //start sub-thread              mythread tt;    //also created a thread     tt.setobjectname ("tt");     tt.start ();}

Can be said to be three threads above, because also contains the main thread, three threads are executed in parallel. Macro-level.


Note: The above code, the main thread will end before the child thread, all the child threads end, the process ends.

The end of a process, to wait for all internal threads to end before it ends.


Iv. the life cycle of a thread


1. When creating an object with a thread class, it can be said that we have created a thread, the thread object that was created

When the start member function is called, the thread starts running, running the run member function body, which participates in the operation

System scheduling, the operating system to each thread a certain time slice time to execute, time slices to the current thread

Stop running, other threads run its time slice, so dispatch, so from the point of view of a single-core CPU, microscopic look, thread

is sequential execution, which switches the execution of each thread by the operating system. One of the non-normal deaths of the thread is due to terminate ()

The member function is caused, so the Terminate member function is not recommended because data integrity is not considered,

A violent kill thread may cause resources to be freed, data incomplete, etc.

Disable invocation.


2, do not call the Terminate () member function to end a thread, how gracefully to end a thread's life time?

(1) Solution ideas:

The end of the run () function is the only way to gracefully terminate a thread because it is the natural death of the thread and the run member function is executed.

The run member function is returned normally, this is called normal death, so a token variable m_tostop (volatile bool) is added to the thread class, which is determined by the value of M_tostop to return from the run () function. The run function returns, for elegant

The end thread. The volatile keyword must be decorated with this flag variable, do not need to compile to optimize, but each time we will go to the memory to take this value, the value is variable, so add volatile.


3, the code is as follows

Class MyThread:p ublic qthread{protected:volatile bool m_tostop;    void run ();    Public:mythread () {m_tostop = false;    } void Stop () {m_tostop = true; }};void Mythread::run () {while (!m_tostop) {}}

The above code, if a while loop in the Run function, determines that the value of the M_tostop variable is true,

The run function will return without executing the while loop, jumping out of the while loop, and the

Method is a good way to end a thread execution in a project, standard gracefully to end a thread.

class mythread :p ublic qthread{protected:    volatile bool m_ Tostop;    void run ()     {         int *p = new int[10000];    //applied for 10000*int size heap space so p points to          for  ( int i = 0; !m_toStop & &  (i < 10); i++ )         {             p[i]  = i * i;                 sleep (1);         }                 delete[] p;    }        public:   &nbsp MyThread ()     {        m_toStop = false;     }    void stop ()     {         m_toStop = true;    }};

int main (void)

{

MyThread T;


T.start ();


Sleep (5000);

T.stop (); Elegant End-Thread


}

This article is from the "Whylinux" blog, make sure to keep this source http://whylinux.blog.51cto.com/10900429/1917910

(73 lessons) multithreaded programming in QT (i)

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.