多线程下载特别容易崩溃

This commit is contained in:
metanoia1989 2021-01-03 21:26:49 +08:00
parent 0b5be2dbfe
commit 7f764bbb8c
6 changed files with 2145 additions and 413 deletions

View File

@ -9,11 +9,13 @@ CONFIG += c++17
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \ SOURCES += \
filedownloadworker.cpp \
main.cpp \ main.cpp \
utils.cpp \ utils.cpp \
widget.cpp widget.cpp
HEADERS += \ HEADERS += \
filedownloadworker.h \
utils.h \ utils.h \
widget.h widget.h

View File

@ -4,3 +4,11 @@
开始下载数据: 0~630426 -> writePos Start 0 开始下载数据: 0~630426 -> writePos Start 0
开始下载数据: 630427~1260853 -> writePos Start 630427 开始下载数据: 630427~1260853 -> writePos Start 630427
开始下载数据: 1260854~1891280 -> writePos Start 1260854 开始下载数据: 1260854~1891280 -> writePos Start 1260854
文件大小为: 89937570
开始下载文件
开始下载数据: " 0~22484391 -> writePos Start 0"
开始下载数据: " 22484392~44968783 -> writePos Start 22484392"
开始下载数据: " 44968784~67453175 -> writePos Start 44968784"
开始下载数据: " 67453176~89937570 -> writePos Start 67453176

View File

@ -0,0 +1,6 @@
#include "filedownloadworker.h"
FileDownloadWorker::FileDownloadWorker(QObject *parent) : QObject(parent)
{
}

View File

@ -0,0 +1,16 @@
#ifndef FILEDOWNLOADWORKER_H
#define FILEDOWNLOADWORKER_H
#include <QObject>
class FileDownloadWorker : public QObject
{
Q_OBJECT
public:
explicit FileDownloadWorker(QObject *parent = nullptr);
signals:
};
#endif // FILEDOWNLOADWORKER_H

File diff suppressed because it is too large Load Diff

View File

@ -164,14 +164,15 @@ void Widget::multiDownload(const QString &url, qint64 fileSize, const QString &f
.arg(pair.first).arg(pair.second).arg(writePos); .arg(pair.first).arg(pair.second).arg(writePos);
connect(reply, &QNetworkReply::readyRead, [&lock, &writePos, &file, &bytesReceived, reply](){ connect(reply, &QNetworkReply::readyRead, [&lock, &writePos, &file, &bytesReceived, reply](){
QByteArray data = reply->readAll(); QByteArray data = reply->readAll();
lock.lock(); {
// qDebug() << "调整文件的数据指针:" << writePos; QMutexLocker mLock(&lock);
file.seek(writePos); // qDebug() << "调整文件的数据指针:" << writePos;
file.write(data); file.seek(writePos);
bytesReceived += data.size(); file.write(data);
qDebug() << QString("%1, %2, %3") bytesReceived += data.size();
.arg(writePos).arg(bytesReceived).arg(data.size()); qDebug() << QString("%1, %2, %3")
lock.unlock(); .arg(writePos).arg(bytesReceived).arg(data.size());
}
writePos += data.size(); writePos += data.size();
}); });
connect(reply, &QNetworkReply::finished, &event, &QEventLoop::quit); connect(reply, &QNetworkReply::finished, &event, &QEventLoop::quit);