search
HomeBackend DevelopmentPHP Tutoriallesson15-QT multi-threading_PHP tutorial

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
<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>
<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>

2. Semaphore

<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>

<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>

<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>


3. Condition variable

<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>

<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>



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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),