Table of Contents
lesson15-QT multi-threading
Home Backend Development PHP Tutorial lesson15-QT multi-threading_PHP tutorial

lesson15-QT multi-threading_PHP tutorial

Jul 12, 2016 am 08:58 AM
android

lesson15-QT multi-threading

1. What is a thread
1. Thread
Process: an executing program, which is the smallest unit of resource allocation
thread : The smallest unit of program execution

The process has many disadvantages. First, because the process is the resource owner, there is a large time and space overhead in creation, undoing and switching, so it is necessary to introduce lightweight processes; second, because of the symmetric multi-process The emergence of processors (SMP) can satisfy multiple running units, but the parallel overhead of multiple processes is too large.

2. The terminology of threads
Concurrency means that at the same time, only one instruction can be executed, but multiple process instructions are executed in rapid rotation, which has the effect of multiple processes executing at the same time from a macro perspective. .
Appears to happen at the same time

Parallelism means that multiple instructions are executed simultaneously on multiple processors at the same time.
True simultaneous occurrence

Synchronization: Calls that are dependent on each other should not "happen at the same time", and synchronization is to prevent those things that "happen at the same time"
The concept of asynchronous is opposite to synchronization. Any two operations that are independent of each other are asynchronous, which indicates that things happen independently

3. Advantages of threads
1), parallelism in developing programs on multi-processors
2), While waiting for slow IO operations, the program can perform other operations to improve concurrency
3). Modular programming can more clearly express the relationship between independent events in the program, with a clear structure
4) and occupy a larger area. Fewer system resources

Multi-threading does not necessarily require multi-processors
Multi-threading technology is often used in GUI programs. One thread is used to respond to the interface, while other threads can handle lengthy operations in the background
Qt’s meta-object system supports communication between objects in different threads using the signal and slot mechanism




2. QT multi-threading
Using multi-threading in Qt is very simple Yes, as long as you subclass QThread, there is a protected type run function in QThread. Multi-threading can be achieved by rewriting the run function.
1. QT threads
Using multi-threading in Qt is very simple. Just subclass QThread and then rewrite the run function to achieve multi-threading

class MyThread:public Thread
{
public:
MyThread();
protected:
void run();
private:
volatile boolean stopped;
}

run function It is started through the start method of the thread. The thread also has the isRunning method to determine whether it is running. The terminate method ends the thread


2. Thread synchronization semaphore
The semaphore prevents the thread from being busy. Waiting is an extension of mutex. Using a semaphore can ensure that two critical codes will not be concurrent. When entering a critical section of code, the thread must obtain the semaphore and release it when exiting. Semaphores can be accessed by multiple threads at the same time.

Qt’s semaphore QSemaphore class:
acquire() is used to acquire resources, free() is used to release resources

Examples of producers and consumers, when producers produce It is necessary to ensure that there is enough space. When consumers consume, they must ensure that there are resources in the space
QSemaphore freeByte(100) The producer has 100 spaces
QSemaphore useByte(0) The consumer has no resources
producer
{
freeByte.acquire()
byte = n
useByte.release()
}
consumer
{
useByte.acquire()
printf byte
freeByte.release()
}


3. Condition variables for thread synchronization
QWaitCondition allows threads to wake up other threads under certain conditions, so that threads do not have to be busy. To wait, the condition variable must be used with the mutex

QMutex mutex; QWaitCondition condition;
condition.wait(&mutex)
condition.wakeAll()
wait function unlocks the mutex , and wait here, the mutex will be re-locked before this function returns.
The wakeAll function will wake up all threads waiting for the mutex


4. Thread priority
The actual task may let a certain thread run first, so you need to set the thread priority class.
The setPriority function can set the priority of the thread, or pass in the priority of the thread in the start function when the thread is started


3. Examples
1. Multi-threading

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#ifndef MYTHREAD_H<br /> </li><li>#define MYTHREAD_H<br /></li><li><br /></li><li>#include <QThread><br /></li><li><br /></li><li>class MyThread : public QThread<br /></li><li>{<br /></li><li>Q_OBJECT<br /></li><li>public:<br /></li><li>MyThread();<br /></li><li>void stop();<br /></li><li>volatile bool stopped;<br /></li><li>protected:<br /></li><li>void run();<br /></li><li>};<br /></li><li>#endif</li></ol>

Copy after login

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#include "myThread.h"<br /> </li><li>#include <QtDebug><br /></li><li><br /></li><li>MyThread::MyThread()<br /></li><li>{<br /></li><li>stopped = false;<br /></li><li>}<br /></li><li><br /></li><li>void MyThread::run()<br /></li><li>{<br /></li><li>int i=0;<br /></li><li>while(!stopped)<br /></li><li>{<br /></li><li>qDebug()<<"thread id:"<QThread::currentThreadId()<<":"<<i;<br /></li><li>i++;<br /></li><li>sleep(2);<br /></li><li>}<br /></li><li>stopped = false;<br /></li><li>}<br /></li><li><br /></li><li>void MyThread::stop()<br /></li><li>{<br /></li><li>stopped = true;<br /></li><li>} </li></ol>

Copy after login

2. Semaphore

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#ifndef PRODUCER_H<br /> </li><li>#define PRODUCER_H<br /></li><li><br /></li><li>#include <QThread><br /></li><li><br /></li><li>class Producer : public QThread<br /></li><li>{<br /></li><li>Q_OBJECT<br /></li><li>public:<br /></li><li>Producer();<br /></li><li>protected:<br /></li><li>void run();<br /></li><li>};<br /></li><li><br /></li><li>#endif</li></ol>

Copy after login

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#ifndef CONSUMER_H<br /> </li><li>#define CONSUMER_H<br /></li><li><br /></li><li>#include <QThread><br /></li><li><br /></li><li>class Consumer : public QThread<br /></li><li>{<br /></li><li>Q_OBJECT<br /></li><li>public:<br /></li><li>Consumer();<br /></li><li>protected:<br /></li><li>void run();<br /></li><li>};<br /></li><li><br /></li><li>#endif</li></ol>

Copy after login

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#include "producer.h"<br /> </li><li>#include "consumer.h"<br /></li><li>#include <QDebug><br /></li><li>#include <QSemaphore><br /></li><li><br /></li><li>#define SIZE 50<br /></li><li>QSemaphore freeByte(SIZE);<br /></li><li>QSemaphore useByte(0);<br /></li><li><br /></li><li>Producer::Producer()<br /></li><li>{<br /></li><li><br /></li><li>}<br /></li><li>void Producer::run()<br /></li><li>{<br /></li><li>for(int i=0; i<SIZE; i++)<br /></li><li>{<br /></li><li>freeByte.acquire();<br /></li><li>qDebug()<<"produer:"<<i;<br /></li><li>useByte.release();<br /></li><li>sleep(1);<br /></li><li>}<br /></li><li>}<br /></li><li>Consumer::Consumer()<br /></li><li>{<br /></li><li><br /></li><li>}<br /></li><li>void Consumer::run()<br /></li><li>{<br /></li><li>for(int i=0; i<SIZE; i++)<br /></li><li>{<br /></li><li>useByte.acquire();<br /></li><li>qDebug()<<"consumer:"<<i;<br /></li><li>freeByte.release();<br /></li><li>sleep(2);<br /></li><li>}<br /></li><li>} </li></ol>

Copy after login


3. Condition variable

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#ifndef THREAD_H<br /> </li><li>#define THREAD_H<br /></li><li><br /></li><li>#include<QThread><br /></li><li><br /></li><li>class Producer : public QThread<br /></li><li>{<br /></li><li>Q_OBJECT<br /></li><li>public:<br /></li><li>Producer();<br /></li><li>protected:<br /></li><li>void run();<br /></li><li>};<br /></li><li><br /></li><li>class Consumer : public QThread<br /></li><li>{<br /></li><li>Q_OBJECT<br /></li><li>public:<br /></li><li>Consumer();<br /></li><li>protected:<br /></li><li>void run();<br /></li><li>};<br /></li><li><br /></li><li>#endif</li></ol>

Copy after login

1

<ol style="margin:0 1px 0 0px;padding-left:40px;" start="1" class="dp-css"><li>#include "thread.h"<br /> </li><li>#include <QDebug><br /></li><li>#include <QMutex><br /></li><li>#include <QWaitCondition><br /></li><li><br /></li><li>QMutex mutex;<br /></li><li>QWaitCondition empty, full;<br /></li><li>int num=0;<br /></li><li>int buffer[50];<br /></li><li>int useByte=0;<br /></li><li><br /></li><li><br /></li><li>Producer::Producer()<br /></li><li>{<br /></li><li><br /></li><li>}<br /></li><li>void Producer::run()<br /></li><li>{<br /></li><li>for(int i=0; i<50; i++)<br /></li><li>{<br /></li><li>mutex.lock();<br /></li><li>if(useByte==50)<br /></li><li>empty.wait(&mutex);<br /></li><li>num++;<br /></li><li>buffer[i] = num;<br /></li><li>qDebug()<<"producer:"<<num;<br /></li><li>useByte++;<br /></li><li>full.wakeAll();<br /></li><li>mutex.unlock();<br /></li><li>sleep(1);<br /></li><li>}<br /></li><li>}<br /></li><li>Consumer::Consumer()<br /></li><li>{<br /></li><li><br /></li><li>}<br /></li><li>void Consumer::run()<br /></li><li>{<br /></li><li>for(int i=0; i<50; i++)<br /></li><li>{<br /></li><li>mutex.lock();<br /></li><li>if(useByte==0)<br /></li><li>full.wait(&mutex);<br /></li><li>qDebug()<<"consumer"<<buffer[i];<br /></li><li>useByte--;<br /></li><li>empty.wakeAll();<br /></li><li>mutex.unlock();<br /></li><li>sleep(2);<br /></li><li>}<br /></li><li>} </li></ol>

Copy after login



www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1103190.htmlTechArticlelesson15-QT Multithreading 1. What is a thread 1. Thread process: an executing program, which is a resource The smallest unit of allocation thread: The smallest unit of program execution. Process appears very...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles