当前位置:网站首页>[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 .
边栏推荐
- 【剑指 Offer】57. 和为s的两个数字
- Ransack组合条件搜索实现
- Market Research - current market situation and future development trend of aircraft audio control panel system
- Les trois principaux points de douleur traités par servicemesh
- C语言,实现三子棋小游戏
- PIP audit: a powerful security vulnerability scanning tool
- 《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
- pip安装whl文件报错:ERROR: ... is not a supported wheel on this platform
- 一周生活
- "New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
猜你喜欢
[shutter] shutter gesture interaction (click event handling | click OnTap | double click | long press | click Cancel | press ontapdown | lift ontapup)
"New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
An overview of the development of affective computing and understanding research
20220702 how do programmers build knowledge systems?
情感计算与理解研究发展概述
pip安裝whl文件報錯:ERROR: ... is not a supported wheel on this platform
Landingsite eband B1 smoke test case
PIP audit: a powerful security vulnerability scanning tool
[staff] Sibelius 7.5.1 score software installation (software download | software installation)
Error in PIP installation WHL file: error: is not a supported wheel on this platform
随机推荐
[shutter] shutter opens a third-party application (url|launcher plug-in search and installation | url| launcher plug-in official example | open browser | open a third-party application)
The failure rate is as high as 80%. What should we do about digital transformation?
[shutter] shutter gesture interaction (small ball following the movement of fingers)
Meibeer company is called "Manhattan Project", and its product name is related to the atomic bomb, which has caused dissatisfaction among Japanese netizens
Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source
地理探测器原理介绍
技术人创业:失败不是成功,但反思是
Daily book CSO advanced road first exposed
记录一下微信、QQ、微博分享web网页功能
Image segmentation using pixellib
Market Research - current situation and future development trend of marine clutch Market
Pointer and string
[shutter] shutter page Jump (route | navigator | page close)
An overview of the development of affective computing and understanding research
Necessary browser plug-ins for network security engineers
100 important knowledge points that SQL must master: using cursors
Share how to make professional hand drawn electronic maps
The book "new programmer 002" is officially on the market! From "new database era" to "software defined car"
"New programmer 003" was officially launched, and the cloud native and digital practical experience of 30+ companies such as Huawei and Alibaba
*C语言期末课程设计*——通讯录管理系统(完整项目+源代码+详细注释)