Qt中多线程使用案列

2023-12-21 22:28
文章标签 使用 qt 多线程 案列

本文主要是介绍Qt中多线程使用案列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Qt中多线程下载大文件

#pragma once#include <QWidget>
#include <QPushButton>
#include "ThreadPool.h"
#include <QProgressBar>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
class MainWindow : public QWidget
{Q_OBJECTpublic:MainWindow(QWidget *parent = Q_NULLPTR);private:void initUI();void initConnect();private:QPushButton*  m_dlBtn;DownLoad::ThreadPool  threadPool;QMap<QString ,std::pair<QLabel*,QProgressBar*> > controlMap;};
#include "MainWindow.h"#include "Task.h"
#include "ThreadPool.h"
MainWindow::MainWindow(QWidget *parent): QWidget(parent)
{initUI();initConnect();
}void MainWindow::initUI()
{m_dlBtn = new QPushButton(this);m_dlBtn->setText(QString("DownLoad"));QVBoxLayout*  layout = new QVBoxLayout();layout->setSpacing(10);layout->setContentsMargins(10, 10, 10, 10);layout->addWidget(m_dlBtn);for (int i = 0; i < 10; i++){DownLoad::Task* task = new DownLoad::Task("http://mirrors.tuna.tsinghua.edu.cn/archlinux/iso/2023.12.01/archlinux-2023.12.01-x86_64.iso", QString("C:/Users/gd09861-hlw/Desktop/11111/archlinux-2023.12.01-x86_64_%1.iso").arg(i), DownLoad::Task::WorkModel::DOWNLOAD);threadPool.push(task);QLabel *label = new QLabel(this);label->setText(QString("%1").arg(i));QProgressBar *progressBar = new QProgressBar(this);controlMap.insert(task->id(), std::make_pair(label, progressBar));QHBoxLayout *hLayout = new QHBoxLayout;hLayout->addWidget(label);hLayout->addWidget(progressBar);layout->addLayout(hLayout);}this->setLayout(layout);
}void MainWindow::initConnect()
{connect(m_dlBtn, &QPushButton::clicked, [&]() {threadPool.startAll();});connect(&threadPool, &DownLoad::ThreadPool::sigUpdateTaskProgress, this, [&](QString id, qint64 bytesR, qint64 bytesT) {controlMap[id].second->setValue((bytesR*100.0f) / (bytesT*1.0f));});connect(&threadPool, &DownLoad::ThreadPool::sigUpdateTaskState, this, [&](QString id,DownLoad::Task::State state) {switch (state){case DownLoad::Task::Start:{controlMap[id].second->setValue(0);}break;case DownLoad::Task::Stop: {controlMap[id].first->setText("Stop");}break;case DownLoad::Task::Finish:controlMap[id].first->setText("Finish");break;case DownLoad::Task::Error:controlMap[id].first->setText("error");break;default:break;}});
}
#ifndef  __TASK_QUEUE_H__
#define  __TASK_QUEUE_H__#include <QObject>
#include <QString>
#include "Task.h"
#include <QQueue>
#include <QMutex>
namespace DownLoad {#define  DEFAULT_THREAD_MAX_COUNT  3class ThreadPool :public QObject{Q_OBJECTpublic:ThreadPool();~ThreadPool();void init();void  push(Task *task);Task* pop();void startAll();void slotUpdateTaskState(QString id, Task::State  state);signals :void sigUpdateTaskProgress(QString id, qint64 bytesReceived, qint64 bytesTotal);void sigUpdateTaskState(QString id, Task::State  state);private:QQueue<Task*>  m_tasks;QList<QThread*>  m_threads;};
};
#endif
#include "ThreadPool.h"
#include <QMutexLocker>
#include <QThread>
#include "Task.h"
DownLoad::ThreadPool::ThreadPool()
{init();
}DownLoad::ThreadPool::~ThreadPool()
{}void DownLoad::ThreadPool::init()
{for (int i = 0; i < DEFAULT_THREAD_MAX_COUNT; i++) {QThread  *thread = new QThread();m_threads.push_back(thread);}
}void DownLoad::ThreadPool::push(Task *task)
{m_tasks.enqueue(task);
}DownLoad::Task* DownLoad::ThreadPool::pop()
{return m_tasks.dequeue();
}void DownLoad::ThreadPool::startAll()
{if (m_threads.isEmpty()) {return;}for (int i = 0; i < m_threads.count(); i++){QThread *  thread = m_threads.at(i);if (thread->isRunning()) {continue;}if (m_tasks.isEmpty()) {return;}Task* task = pop();task->moveToThread(thread);connect(task, &Task::sigUpdateProgress, this, &ThreadPool::sigUpdateTaskProgress, Qt::QueuedConnection);connect(task, &Task::sigUpdateState, this, &ThreadPool::slotUpdateTaskState, Qt::QueuedConnection);connect(thread, &QThread::started, task, &Task::slotDoWork,Qt::QueuedConnection);connect(thread, &QThread::finished, task, &Task::deleteLater);thread->start();}
}void DownLoad::ThreadPool::slotUpdateTaskState(QString id, Task::State  state)
{emit  sigUpdateTaskState(id, state);if (state == DownLoad::Task::Finish || state == DownLoad::Task::Error||state==DownLoad::Task::Stop) {startAll();}
}
#ifndef  __TASK_H__
#define  __TASK_H__#include <QObject>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QSharedPointer>
#include <QUrl>
#include <QString>
#include <QEventLoop>
#include <QMetaType>
namespace  DownLoad {
#define  DOWNLOAD_FILE_SUFFIX  ".tmp"class Task :public QObject{Q_OBJECTpublic:enum WorkModel{UPLOAD,DOWNLOAD,};enum State{Start,Stop,Finish,Error,};QString  id();Task(const QString &strUrl, const QString &filePath, const WorkModel& workModel);~Task();void setSupportBreakPoint(bool isSupport);QString lastError();signals:void sigUpdateState(QString id,State  state);void sigUpdateProgress(QString id,qint64 bytesReceived, qint64 bytesTotal);public slots:void slotDoWork();void slotStopWork();void slotCancelWork();protected:void removeTmpFile(const QString &filePath);void slotUpdateProgress(qint64 bytesReceived, qint64 bytesTotal);void slotWriteFile();void slotFinish();void slotError(QNetworkReply::NetworkError code);protected:void doDownWork();void doUploadWork();private:QNetworkReply*				 m_reply = nullptr;QNetworkRequest				 m_request;QNetworkAccessManager		 m_manager;QUrl m_url;QString m_filePath = "";WorkModel  m_workModel = UPLOAD;QSharedPointer<QEventLoop>  m_loop;bool m_bSupportBPoint = false;qint64  m_bytesReceived;qint64  m_bytesTotal;qint64  m_bytesCurrentReceived;QString m_error = "";QString m_id = "";};};
Q_DECLARE_METATYPE(DownLoad::Task::State);#endif     //__TASK_H__
#include "Task.h"
#include <QFileInfo>
#include <QUuid>
#include <QDebug>
#include <QThread>
#include <QDir>QString DownLoad::Task::id()
{return m_id;
}DownLoad::Task::Task(const QString &strUrl, const QString &filePath, const WorkModel& workModel):QObject(nullptr), m_url(strUrl), m_filePath(filePath), m_workModel(workModel),m_bytesTotal(0),m_bytesReceived(0),m_bytesCurrentReceived(0),m_bSupportBPoint(false),m_id(QUuid::createUuid().toString())
{}DownLoad::Task::~Task()
{if (m_reply) {m_reply->deleteLater();}}void DownLoad::Task::setSupportBreakPoint(bool isSupport)
{m_bSupportBPoint = isSupport;
}QString DownLoad::Task::lastError()
{return m_error;
}void DownLoad::Task::slotDoWork()
{qDebug() << "UUID:" << m_id << "TID:" << QThread::currentThreadId()<<"\t"<<m_filePath;if (m_url.isEmpty() || m_filePath.isEmpty()) {return;}switch (m_workModel){case DownLoad::Task::UPLOAD:doUploadWork();break;case DownLoad::Task::DOWNLOAD:doDownWork();break;default:break;}
}void DownLoad::Task::slotStopWork()
{m_bytesCurrentReceived += m_bytesReceived;if (m_reply) {disconnect(m_reply, 0, this, 0);m_reply->abort();m_reply->deleteLater();m_reply = nullptr;this->thread()->exit();emit  sigUpdateState(m_id,State::Stop);}
}void DownLoad::Task::slotCancelWork()
{slotStopWork();m_bytesCurrentReceived = 0;m_bytesReceived = 0;m_bytesTotal = 0;removeTmpFile(m_filePath + DOWNLOAD_FILE_SUFFIX);
}void DownLoad::Task::removeTmpFile(const QString &filePath)
{QFileInfo fileInfo(filePath);if (fileInfo.exists()) {QFile::remove(filePath);}
}void DownLoad::Task::slotUpdateProgress(qint64 bytesReceived, qint64 bytesTotal)
{m_bytesReceived = bytesReceived;m_bytesTotal = bytesTotal;emit  sigUpdateProgress(m_id,m_bytesReceived + m_bytesCurrentReceived, m_bytesTotal + m_bytesCurrentReceived);
}void DownLoad::Task::slotWriteFile()
{QFile file(m_filePath + DOWNLOAD_FILE_SUFFIX);QDir dir=QFileInfo(m_filePath + DOWNLOAD_FILE_SUFFIX).absoluteDir();if (!dir.exists()) {dir.mkpath(dir.absolutePath());}if (file.open(QIODevice::WriteOnly | QIODevice::Append)) {file.write(m_reply->readAll());}file.close();
}void DownLoad::Task::slotFinish()
{QVariant  code = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);qDebug() << "Error Code:" << code.toInt();if (m_reply->error() == QNetworkReply::NoError) {QFileInfo fileInfo(m_filePath + DOWNLOAD_FILE_SUFFIX);if (fileInfo.exists()) {QFile::rename(m_filePath+DOWNLOAD_FILE_SUFFIX,m_filePath);this->thread()->exit();emit sigUpdateState(m_id, State::Finish);}}else { m_error = m_reply->errorString();this->thread()->exit();emit sigUpdateState(m_id, State::Error);}
}void DownLoad::Task::slotError(QNetworkReply::NetworkError code)
{if (code == QNetworkReply::NoError)return;slotStopWork();removeTmpFile(m_filePath + DOWNLOAD_FILE_SUFFIX);this->thread()->exit();emit	 sigUpdateState(m_id, State::Error);m_error = m_reply->errorString();}void DownLoad::Task::doDownWork()
{if (m_bytesCurrentReceived <= 0) {removeTmpFile(m_filePath + DOWNLOAD_FILE_SUFFIX);}QFileInfo  fileInfo(m_filePath + DOWNLOAD_FILE_SUFFIX);if (fileInfo.exists()) {m_bytesCurrentReceived = fileInfo.size();}QString strUrl = m_url.toString();m_request.setUrl(strUrl);if (m_bSupportBPoint) {QString strRange = QString("bytes=%1-").arg(m_bytesCurrentReceived);m_request.setRawHeader("Range", strRange.toLatin1());}m_reply = m_manager.get(m_request);connect(m_reply, &QNetworkReply::downloadProgress, this, &Task::slotUpdateProgress);connect(m_reply, &QNetworkReply::readyRead, this, &Task::slotWriteFile);connect(m_reply, &QNetworkReply::finished, this, &Task::slotFinish);connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError code)), this,SLOT(slotError(QNetworkReply::NetworkError code)));
}void DownLoad::Task::doUploadWork()
{}

上处代码运行可以看出,QThread 中,每次调用start() 时 ,都会改变线程ID 在这里插入图片描述
因此,QT 的线程开启就是在创建线程,只不过其中含有事件循环机制。另外对于自定义类型,必须指定队列连接。
运行后在这里插入图片描述

这篇关于Qt中多线程使用案列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/521689

相关文章

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁

ModelMapper基本使用和常见场景示例详解

《ModelMapper基本使用和常见场景示例详解》ModelMapper是Java对象映射库,支持自动映射、自定义规则、集合转换及高级配置(如匹配策略、转换器),可集成SpringBoot,减少样板... 目录1. 添加依赖2. 基本用法示例:简单对象映射3. 自定义映射规则4. 集合映射5. 高级配置匹

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

嵌入式数据库SQLite 3配置使用讲解

《嵌入式数据库SQLite3配置使用讲解》本文强调嵌入式项目中SQLite3数据库的重要性,因其零配置、轻量级、跨平台及事务处理特性,可保障数据溯源与责任明确,详细讲解安装配置、基础语法及SQLit... 目录0、惨痛教训1、SQLite3环境配置(1)、下载安装SQLite库(2)、解压下载的文件(3)、

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

Springboot如何正确使用AOP问题

《Springboot如何正确使用AOP问题》:本文主要介绍Springboot如何正确使用AOP问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录​一、AOP概念二、切点表达式​execution表达式案例三、AOP通知四、springboot中使用AOP导出

Navicat数据表的数据添加,删除及使用sql完成数据的添加过程

《Navicat数据表的数据添加,删除及使用sql完成数据的添加过程》:本文主要介绍Navicat数据表的数据添加,删除及使用sql完成数据的添加过程,具有很好的参考价值,希望对大家有所帮助,如有... 目录Navicat数据表数据添加,删除及使用sql完成数据添加选中操作的表则出现如下界面,查看左下角从左

python 常见数学公式函数使用详解(最新推荐)

《python常见数学公式函数使用详解(最新推荐)》文章介绍了Python的数学计算工具,涵盖内置函数、math/cmath标准库及numpy/scipy/sympy第三方库,支持从基础算术到复杂数... 目录python 数学公式与函数大全1. 基本数学运算1.1 算术运算1.2 分数与小数2. 数学函数