当前位置:网站首页>[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 .
边栏推荐
- 基于ASP.net的手机销售管理系统(二手手机销售管理系统)+ASP.NET+C#语言+VS2010+数据库可以用于课设、毕设学习
- Technological Entrepreneurship: failure is not success, but reflection is
- 540. Single element in ordered array
- LightGBM原理及天文数据中的应用
- ServiceMesh主要解决的三大痛點
- Landingsite eband B1 smoke test case
- Destroy in beforedestroy invalid value in localstorage
- About test cases
- Unity3d learning notes 4 - create mesh advanced interface
- [Jianzhi offer] 56 - ii Number of occurrences of numbers in the array II
猜你喜欢

Introduction to the principle of geographical detector

From "bronze" to "King", there are three secrets of enterprise digitalization

20220702-程序员如何构建知识体系?

LightGBM原理及天文数据中的应用
![[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)](/img/f7/cb41d159e5c5ef3f4f1b9468d52ccc.jpg)
[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)

New feature of go1.18: introduce new netip Network Library

CVPR论文解读 | 弱监督的高保真服饰模特生成

Error in PIP installation WHL file: error: is not a supported wheel on this platform

Technical solution of vision and manipulator calibration system

A specially designed loss is used to deal with data sets with unbalanced categories
随机推荐
tinymce可视化编辑器增加百度地图插件
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
Chargement de l'image pyqt après décodage et codage de l'image
情感计算与理解研究发展概述
540. Single element in ordered array
Market Research - current situation and future development trend of carob chocolate market
Ransack组合条件搜索实现
Share how to make professional hand drawn electronic maps
Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
【剑指 Offer】56 - I. 数组中数字出现的次数
[shutter] shutter application theme (themedata | dynamic modification theme)
Try to get property'num for PHP database data reading_ rows' of non-object?
[leetcode] sword finger offer 11 Rotate the minimum number of the array
《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!
Landingsite eband B1 smoke test case
Image segmentation using pixellib
Market Research - current market situation and future development trend of high tibial osteotomy plate
Secondary development of ANSYS APDL: post processing uses command flow to analyze the result file
Evolution of messaging and streaming systems under the native tide of open source cloud