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 的线程开启就是在创建线程,只不过其中含有事件循环机制。另外对于自定义类型,必须指定队列连接。
运行后在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/236488.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

el-table 实现行拖拽排序

element ui 表格实现拖拽排序的功能&#xff0c;可以借助第三方插件Sortablejs来实现。 引入sortablejs npm install sortablejs --save组件中使用 import Sortable from sortablejs;<el-table ref"el-table":data"listData" row-key"id" …

【C++】new 和 delete

目录 一 引言 二 new 三 delete 四 new和delete操作自定义类型 五 operator new与operator delete函数 六 new和delete的实现原理 1 内置类型 2 自定义类型 1 new的原理 2 delete的原理 3 new T[N]的原理 4 delete[]的原理 七 定位new表达式(placement-new) 八 …

如何使用Docker搭建青龙面板并结合内网穿透工具发布至公网可访问

文章目录 一、前期准备本教程环境为&#xff1a;Centos7&#xff0c;可以跑Docker的系统都可以使用。本教程使用Docker部署青龙&#xff0c;如何安装Docker详见&#xff1a; 二、安装青龙面板三、映射本地部署的青龙面板至公网四、使用固定公网地址访问本地部署的青龙面板 正文…

期货高低板(期货价格飘升,市场掀起高低潮流)

什么是期货高低板&#xff1f; 期货是由交易所统一交易的标准化合约&#xff0c;商品的价格是通过供求关系来决定的。高低板则是期货交易中的常见现象&#xff0c;它表示了在交易过程中&#xff0c;价格波动超过了可设定的最高或最低价&#xff0c;于是交易系统便会出现高板或…

​Halcon机器视觉软件学习指南

引言 Halcon是由德国MVTec软件公司开发的一款领先的机器视觉软件&#xff0c;广泛应用于工业检测、图像分析、医疗图像处理等领域。对于大学生和初学者而言&#xff0c;学习Halcon不仅能够提升技术层面的能力&#xff0c;还能够增强未来的就业竞争力。本文将为您提供一个系统的…

Git 储藏(stash)用法

储藏的基本用法 保存当前的更改 1、查看储藏 git stash list2、更改保存到一个储藏中&#xff1a; git stash save "info"其中&#xff0c;“info” 是可选的注释信息&#xff0c;可以简要描述这个储藏的内容。 3、恢复之前保存的更改 可以使用下面的命令将之前…

安全狗云原生安全-云甲·云原生容器安全管理系统

随着云计算的快速发展&#xff0c;容器技术逐渐成为主流。然而&#xff0c;随着容器的普及&#xff0c;安全问题也日益突出。为了解决这一问题&#xff0c;安全狗推出了云原生容器安全管理系统——云甲。 云甲是安全狗云原生安全的重要组成部分&#xff0c;它采用了先进的云原生…

Jenkins 构建环境指南

目录 Delete workspace before build starts&#xff08;常用&#xff09; Use secret text(s) or file(s) &#xff08;常用&#xff09; Add timestamps to the Console Output &#xff08;常用&#xff09; Inspect build log for published build scans Terminate a …

什么是“人机协同”机器学习?

“人机协同”&#xff08;HITL&#xff09;是人工智能的一个分支&#xff0c;它同时利用人类智能和机器智能来创建机器学习模型。在传统的“人机协同”方法中&#xff0c;人们会参与一个良性循环&#xff0c;在其中训练、调整和测试特定算法。通常&#xff0c;它的工作方式如下…

vscode开发python环境配置

前言 vscode作为一款好用的轻量级代码编辑器&#xff0c;不仅支持代码调试&#xff0c;而且还有丰富的插件库&#xff0c;可以说是免费好用&#xff0c;对于初学者来说用来写写python是再合适不过了。下面就推荐几款个人觉得还不错的插件&#xff0c;希望可以帮助大家更好地写…

亚信安慧AntDB:支撑中国广电5G业务的数据库之力

自2019年6月获得5G牌照以来&#xff0c;中国广电积极利用700MHz频谱资源&#xff0c;迅速崛起为第四大运营商&#xff0c;标志着其在数字通信领域取得的巨大成就。通过与中国移动紧密合作&#xff0c;共建共享基站已超过400万座&#xff0c;为实现自主运营和差异化竞争提供了坚…

淘宝商品评论:商家了解市场趋势和竞争状况的窗口

淘宝商品评论是消费者对购买商品的反馈和评价&#xff0c;是商家了解市场趋势、消费者需求以及竞争状况的重要窗口。通过对商品评论的深入研究和分析&#xff0c;商家可以获取有价值的市场信息和用户需求&#xff0c;从而调整产品策略、优化营销方案以及制定更具针对性的市场竞…

飞书+ChatGPT搭建智能AI助手,无公网ip实现公网访问飞书聊天界面

飞书ChatGPT搭建智能AI助手&#xff0c;无公网ip实现公网访问飞书聊天界面 前言环境列表1.飞书设置2.克隆feishu-chatgpt项目3.配置config.yaml文件4.运行feishu-chatgpt项目5.安装cpolar内网穿透6.固定公网地址7.机器人权限配置8.创建版本9.创建测试企业10. 机器人测试 前言 …

光模块市场分析与发展趋势预测

光模块是光通信领域的重要组成部分&#xff0c;随着数字经济&#xff0c;大数据&#xff0c;云计算&#xff0c;人工智能等行业的兴起&#xff0c;光模块市场经历了快速发展&#xff0c;逐渐在数据中心、无线回传、电信传输等应用场景中得到广泛应用。本文将基于当前光模块全球…

Android Studio打包有哪些优势

大家好&#xff0c;现在移动应用程序的快速发展&#xff0c;开发者需要一个强大又可靠的开发环境来创建和打包高质量的 Android 应用程序。Android Studio 是一款由 Google 官方开发的 Android 应用程序开发环境&#xff0c;提供了许多的优势和便利&#xff0c;那究竟都有哪些优…

基于51的智能交通信号灯设计

文章目录 概要仿真图程序总结 资料下载地址&#xff1a;基于51的智能交通信号灯设计 概要 可实现东西、南北两个方向的红、黄、绿灯按设定的时间亮灭&#xff0c;用以指引交通通行&#xff0c;以倒计时方向显示时间。红、黄、绿交通灯的变化规律为&#xff1a; 1&#xff09…

ros2/ros 4轮2驱机器人xacro/urdf文件示例代码

这个实验中最重要的是&#xff1a;colcon build 之后要记得source install/setup.bash.否则修改的文件是不会更新的。知道了吧 <robot name"half" xmlns:xacro"http://wiki.ros.org/wiki/xacro"><xacro:property name"PI" value"3…

Django 简单图书管理系统

一、图书需求 1. 书籍book_index.html中有超链接&#xff1a;查看所有的书籍列表book_list.html页面 2. 书籍book_list.html中显示所有的书名&#xff0c;有超链接&#xff1a;查看本书籍详情book_detail.html(通过书籍ID)页面 3. 书籍book_detail.html中书的作者和出版社&…

2023年全球软件开发大会(QCon北京站2023)2月-核心PPT资料下载

一、峰会简介 本次活动聚焦云原生、分布式数据库、现代数据技术栈一系列前沿技术与实践&#xff0c;为技术团队负责人、架构师、开发人员等提供了技术学习与交流的平台。 本次峰会包含&#xff1a;AI基础架构、DevOps流程与实践、ML模型效率与易用性、测试环境治理、大规模集…

Nginx 安装(源码编译安装)

Nginx服务器提供了Windows和Linux版本&#xff0c;本文为Linux环境下Nginx服务器的详细安装步骤。 安装环境&#xff1a; Linux服务器操作系统&#xff1a;CentOs 8.1.1911 Nginx版本&#xff1a;1.21.4&#xff08;Linux&#xff09; 安装步骤&#xff1a; 1、安装GCC、aut…