35.qt-Multithreading

Source: Internet
Author: User

Differences in procedures and processes

    • The process is dynamic and the program is static
    • The process is temporary , the program is permanent , and the process is obtained by running the program
    • A program is a data file, a process is an in-memory dynamic running entity used to store data segments, code snippets, pointers, etc.

The relationship between procedures and processes

    • A program may correspond to multiple processes
    • A process may contain multiple programs, such as when a program relies on multiple other dynamic libraries


Relationship of processes and threads

    • Process is the basic unit of operating system resource allocation
    • Threads are the basic unit of operating system dispatch execution
    • Each process contains 1 to multiple threads , and each thread can share the resources of a process
    • A thread is also the basic unit of CPU dispatch and dispatch, which is a smaller unit that can run independently than a process.
    • Threads cannot be separated from a process and can only be dependent on process processes
    • You can create and revoke other threads in any thread.
    • A thread dead is equal to the entire process to die, so the multi-process program is more robust than multi-threaded programs, the disadvantage is that the process switch, the efficiency is poor

For example, when multiple files are downloaded, the download-related process creates multiple threads, each of which downloads a file


Multi-threaded programming in QT
The threads in QT exist in the form of objects (inherited from the Qthread Class) .
Among the common member functions of the Qthread class are:

voidrun ();//The thread body function, which requires the user to customize what the function does, can also use Exec () to implement the event loopvoidfinished () [signal]//a signal member function that indicates that the thread has finished executing and has already gone in the run () function.voidstart () [slot]//The start function will execute the run () function and transmit the signal started ()voidstarted () [signal]//a signal member function that indicates that the thread has startedvoidterminate () [slot]//forces the end of an ongoing thread (not recommended because resource release is not considered) and emits a signal terminated ()voidquit ()//tells the thread that the event loop exits and returns 0 for success, equivalent to calling Qthread::exit (0). voidqthread::terminated () [Signal]//a signal member function that indicates that the thread has stoppedSleep (unsignedLongsecs), Msleep (), Usleep () ,//dormant current thread seconds, milliseconds, subtlevoidSetPriority (priority priority);//sets the running thread priority, which must be set after the start () thread is calledBOOLIsfinished ()Const //whether the thread endsBOOLIsRunning ()Const //whether the thread is runningBOOLWait (unsignedLongTime =Ulong_max);//blocking waits for thread execution to end, if time (in milliseconds) ends, the thread is not finished, returns false, otherwise true, if time= Ulong_max, it means waiting

multithreaded Example

classMyThread: Publicqthread{protected:    voidrun () {qdebug ()<< This->objectname () <<"Priority :"<< This-Priority ();  for(intI=0;i<3; i++) {qdebug ()<< This->objectname () <<":"<<i; Sleep (1); }    }};intMainintargcChar*argv[])   {Qapplication A (ARGC,ARGV);   MyThread T1; T1.setobjectname ("T1");   T1.start ();   T1.setpriority (qthread::highpriority);   MyThread T2; T2.setobjectname ("T2");   T2.start (); returna.exec ();}

Print:

"T1"Priority4 "T1":0 "T2"Priority7 "T2":0 "T1":1 "T2":1 "T2":2 "T1":2


Multithreading-terminating example
In multithreading, it is generally a custom End function to end a process , as in the following example:

classSample: Publicqthread{protected:    volatile BOOLM_tostop; voidrun () {qdebug ()<< ObjectName () <<": Begin"; int* p =New int[10000];  for(intI=0;!m_tostop && (i<Ten); i++) {qdebug ()<< ObjectName () <<" : "<<i; P[i]= i * I *i; Msleep ( -);        } delete[] P; Qdebug ()<< ObjectName () <<": End"; } Public: Sample () {m_tostop=false; }    voidStop () {m_tostop=true; }};intMainintargcChar*argv[])    {Qcoreapplication A (argc, argv); Qdebug ()<<"Main begin";    Sample T; T.setobjectname ("T");    T.start ();  for(intI=0; i<100000; i++)    {         for(intj=0; j<10000; J + +) {}} t.stop (); Qdebug ()<<"Main End"; returna.exec ();}

Multi-threaded synchronization
When multiple threads are executing, it is possible that one thread will need to wait for the result of another thread to execute, and can pass the wait () member function implementation, waiting for another thread to finish, as shown in:


Multi-threaded Mutex Qmutex
When a global shared resource is called by multiple threads at the same time, the resource is called a critical resource , and the resource needs to use the Qmutex mutex class to ensure mutual exclusion between threads and avoid unexpected problems when accessing critical resources at the same time.
The key member functions in Qmutex are as follows:

void Lock (); // Gets the lock, if the lock is already fetched by another thread, it will block and while waiting for the lock to be released BOOL Trylock (); // An attempt is made to acquire a lock, and if a lock is obtained, the function returns True if the other thread locks the mutex, the function returns false immediately.  void  unlock (); // Release Lock

Example:

QString g_res=""; Qmutex G_mutex;classAddthread: Publicqthread{protected:    voidrun () { while(1) {G_mutex.Lock(); G_res.append ("1"); Qdebug ()<<"Addthread:"<<G_res;            G_mutex.unlock (); Msleep (1); }    }};classMinusthread: Publicqthread{protected:    voidrun () { while(1) {G_mutex.Lock(); if(g_res!="") {G_res.remove (0,1); Qdebug ()<<"Minusthread:"<<G_res;            } g_mutex.unlock (); Msleep (1); }    }};intMainintargcChar*argv[])    {Qapplication A (ARGC,ARGV);    Addthread T1;    Minusthread T2;    T1.start ();    T2.start (); returna.exec ();}

If there are many different critical resources, such as: g_res1, G_res2, G_RES3...G_RESN
The corresponding thread lock also needs to be assigned the same sequence number: g_mutex1, G_mutex2, G_mute3...g_mutexn
Note: If multiple critical resources correspond to only one thread lock, the concurrency efficiency is reduced

Multi-threaded Semaphore Qsemaphore
The semaphore is a special lock that internally passes a resource value so that n threads can access critical resources at the same time
The key member functions in Qsemaphore are as follows:

voidAcquire (intn =1 );//an attempt was made to acquire N resources protected by semaphores. If n is unavailable, the call will block until sufficient resources are available. voidTryacquire (intn =1 );//An attempt was made to acquire N resources protected by semaphores and return true on success. If not available, the call returns false immediately and does not require any resources to be obtained. intavailable ();//returns the amount of resources currently available for semaphoresvoidRelease (intn =1 );//releases n resources protected by semaphores. 

Example:

Qsemaphore SEM (5);//sem.available () = = 5Sem.acquire (3);//sem.available () = = 2Sem.acquire (2);//sem.available () = = 0Sem.release (5);//sem.available () = = 5Sem.release (5);//sem.available () = = TenSem.tryacquire (1);//sem.available () = = 9, returns TrueSem.tryacquire ( -);//sem.available () = = 9, returns false

35.qt-Multithreading

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.