当前位置:网站首页>[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
[QT] Q multithreaded development - Analysis of multithreaded application examples (Mandelbrot)
2022-07-02 22:26:00 【iriczhao】
Qt- Multi thread application example analysis (Mandelbrot)
List of articles
One 、 Write it at the front
The content of this article is : About Qt Multithreading applications of , The way to create a thread is : Subclass QThread Create thread , heavy load run() Function to implement multithreading .
( notes ) All the code in this article comes from the official example 《Mandelbrot Example》
《Mandelbrot Example》 The example contains two classes :
1、RenderThread It's a QThread Subclass , Used to present Mandelbrot aggregate .
2、MandelbrotWidget It's a QWidget Subclass , Used to display Mandelbrot aggregate , And bind the mouse zoom and scroll event processing functions .
Two 、RendThread The definition of a class
#include <QMutex>
#include <QSize>
#include <QThread>
#include <QWaitCondition>
QT_BEGIN_NAMESPACE
class QImage;
QT_END_NAMESPACE
//! [0]
class RenderThread : public QThread
{
Q_OBJECT
public:
RenderThread(QObject *parent = nullptr);
~RenderThread();
void render(double centerX, double centerY, double scaleFactor, QSize resultSize);
signals:
void renderedImage(const QImage &image, double scaleFactor);
protected:
void run() override;
private:
uint rgbFromWaveLength(double wave);
QMutex mutex;
QWaitCondition condition;
double centerX;
double centerY;
double scaleFactor;
QSize resultSize;
bool restart;
bool abort;
enum {
ColormapSize = 512 };
uint colormap[ColormapSize];
};
1、 This class inherits QThread, So it can run in a separate thread . In addition to constructors and destructors ,render() Is the only public function . Whenever a thread renders an image , Will send out renderedImage() The signal .renderedImage() The signal will be connected to MandelbrotWidget Class updatePixmap Slot function connected , Used to update the QPixmap. For convenience MandelbrotWidget Class paintEvent() Draw event function pairs through RenderThread Thread rendered Pixmap draw . The following code snippet :
connect(&thread, &RenderThread::renderedImage,this, &MandelbrotWidget::updatePixmap);
2、 stay QThread Re implement protected run() function , Call it automatically when the thread starts .
3、 In the private part , There is one QMutex、 One QWaitCondition And some other data members . Mutexes protect another data member .
(2-1)run() Function implementation
void RenderThread::run()
{
forever {
mutex.lock();
QSize resultSize = this->resultSize;
double scaleFactor = this->scaleFactor;
double centerX = this->centerX;
double centerY = this->centerY;
mutex.unlock();
int halfWidth = resultSize.width() / 2;
int halfHeight = resultSize.height() / 2;
QImage image(resultSize, QImage::Format_RGB32);
const int NumPasses = 8;
int pass = 0;
while (pass < NumPasses) {
const int MaxIterations = (1 << (2 * pass + 6)) + 32;
const int Limit = 4;
bool allBlack = true;
for (int y = -halfHeight; y < halfHeight; ++y) {
if (restart)
break;
if (abort)
return;
uint *scanLine =
reinterpret_cast<uint *>(image.scanLine(y + halfHeight));
double ay = centerY + (y * scaleFactor);
for (int x = -halfWidth; x < halfWidth; ++x) {
double ax = centerX + (x * scaleFactor);
double a1 = ax;
double b1 = ay;
int numIterations = 0;
do {
++numIterations;
double a2 = (a1 * a1) - (b1 * b1) + ax;
double b2 = (2 * a1 * b1) + ay;
if ((a2 * a2) + (b2 * b2) > Limit)
break;
++numIterations;
a1 = (a2 * a2) - (b2 * b2) + ax;
b1 = (2 * a2 * b2) + ay;
if ((a1 * a1) + (b1 * b1) > Limit)
break;
} while (numIterations < MaxIterations);
if (numIterations < MaxIterations) {
*scanLine++ = colormap[numIterations % ColormapSize];
allBlack = false;
} else {
*scanLine++ = qRgb(0, 0, 0);
}
}
}//for END
/* After the data is calculated Handle */
if (allBlack && pass == 0) {
pass = 4;
} else {
if (!restart)
emit renderedImage(image, scaleFactor); /* issue renderImage() The signal */
++pass;
}
}//While END
mutex.lock();
if (!restart)
condition.wait(&mutex);
restart = false;
mutex.unlock();
}
}
(2-2)render() Implementation of function
void RenderThread::render(double centerX, double centerY, double scaleFactor,
QSize resultSize)
{
QMutexLocker locker(&mutex);
this->centerX = centerX;
this->centerY = centerY;
this->scaleFactor = scaleFactor;
this->resultSize = resultSize;
if (!isRunning()) {
start(LowPriority);
} else {
restart = true;
condition.wakeOne();
}
}
3、 ... and 、MandelbrotWidget The definition of a class
class MandelbrotWidget : public QWidget
{
Q_OBJECT
public:
MandelbrotWidget(QWidget *parent = nullptr);
protected:
void paintEvent(QPaintEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
void keyPressEvent(QKeyEvent *event) override;
#if QT_CONFIG(wheelevent)
void wheelEvent(QWheelEvent *event) override;
#endif
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
private slots:
void updatePixmap(const QImage &image, double scaleFactor);
void zoom(double zoomFactor);
private:
void scroll(int deltaX, int deltaY);
RenderThread thread;
QPixmap pixmap;
QPoint pixmapOffset;
QPoint lastDragPos;
double centerX;
double centerY;
double pixmapScale;
double curScale;
};
Four 、 summary
1、RendThread Class and MandelbrotWidget Classes are associated through signals and slots : Used to update the MandelbrotWidget Class Pixmap data , And then in paintEvent() Draw in the drawing event function .
2、MandelbrotWidget Class by calling RendThread Class render(double centerX, double centerY, double scaleFactor, QSize resultSize) Member function direction RendThread Class and start RendThread Class thread to calculate .
3、Qt in Widgets parts ( for example QPushButton、QLabel etc. ) Cannot create in other threads , Only in GUI Create... In thread .
边栏推荐
- Market Research - current market situation and future development trend of high tibial osteotomy plate
- SQL必需掌握的100个重要知识点:管理事务处理
- Chargement de l'image pyqt après décodage et codage de l'image
- Basic concepts of image and deep understanding of yuv/rgb
- [shutter] shutter layout component (wrap component | expanded component)
- Market Research - current market situation and future development trend of aircraft wireless intercom system
- Blue Bridge Cup Eliminate last one (bit operation, code completion)
- App page sharing password rails implementation
- Market Research - current market situation and future development trend of genome editing mutation detection kit
- Leetcode theme [array] -169- most elements
猜你喜欢

Blue Bridge Cup Winter vacation homework (DFS backtracking + pruning)

Basic concepts of image and deep understanding of yuv/rgb

Secondary development of ANSYS APDL: post processing uses command flow to analyze the result file

Gee: (II) resampling the image

Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?

Promise optimized callback hell

Technical solution of vision and manipulator calibration system

Reading experience of just because
![[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)](/img/27/8594ba0b49d5008b7469967babed17.jpg)
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)

Scrcpy this software solves the problem of sharing mobile screen with colleagues | community essay solicitation
随机推荐
关于PHP-数据库的 数据读取,Trying to get property 'num_rows' of non-object?
VictoriaMetrics 简介
腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?
Daily book CSO advanced road first exposed
【leetcode】1380. Lucky number in matrix
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
地理探测器原理介绍
Basic concepts of image and deep understanding of yuv/rgb
情感计算与理解研究发展概述
发现你看不到的物体!南开&武大&ETH提出用于伪装目标检测SINet,代码已开源!...
Redis distributed lock failure, I can't help but want to burst
Technical solution of vision and manipulator calibration system
A week's life
Hanoi Tower problem
Market Research - current situation and future development trend of marine clutch Market
100 important knowledge points that SQL must master: management transaction processing
Infrastructure is code: a change is coming
From personal heroes to versatile developers, the era of programmer 3.0 is coming
pip安装whl文件报错:ERROR: ... is not a supported wheel on this platform
[shutter] shutter resource file use (import resource pictures | use image resources)