2

我在使用 QNetworkAccessManager(使用 Qt)时遇到了一些内存泄漏问题。我调用的请求越多,分配的内存就越多。这是有道理的,但对我来说不是这样。我打电话,比如说16个请求,然后一旦网络回复命中16次,我就调用下一个16次。用这种方法,这不会调节内存吗?出于某种原因,它不是,并且随着更多的调用,内存稳步增加。在线程中有这个会影响这个吗?

标题:

#include <QThread>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QSemaphore>
#include <QPixmap>
#include <QMutex>
#include <QDebug>

#include "winnames.h"

#define MAX_REQUEST_COUNT 16

class Downloader : public QThread
{
    Q_OBJECT
public:
    explicit Downloader(QObject *parent = 0);
    void start(Priority = InheritPriority);

signals:
    void PictureDownloaded(QPixmap picture, QString id);

public slots:
    void networkReply(QNetworkReply*);

private:
    void startDownloads();

    QString titleID;
    QNetworkAccessManager *manager;

    int amount;
};

共产党:

#include "downloader.h"

Downloader::Downloader(QObject *parent) : QThread(parent)
{
    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(networkReply(QNetworkReply*)));
}
void Downloader::start(Priority p)
{
    amount = 0;
    titleID = "50";
    startDownloads();
}

void Downloader::startDownloads()
{
    const int searchValues[] = {0, 0x400, 0x1000, 0x8000, 0xFFFF};
    for (int x = 0; x < 4; x++)
    {
        int num = searchValues[x] + amount;
        if (num >= searchValues[x + 1])
            continue;

        for (int i = 0; i < MAX_REQUEST_COUNT; i++)
            manager->get(QNetworkRequest(QUrl("http://my.url/" + titleID.toUpper() + "/someDir/" + QString("%1").arg(num + i, 4, 16, QChar('0')).toUpper())));
    }
}

void Downloader::networkReply(QNetworkReply *reply)
{
    if (reply->bytesAvailable() != 0)
    {
        QPixmap pixmap;
        pixmap.loadFromData(reply->readAll(), "PNG");
        if (!pixmap.isNull())
            emit PictureDownloaded(pixmap, titleID + reply->url().toString().mid(reply->url().toString().length() - 4));
    }
    reply->deleteLater();
    reply->close();

    QMutex m;
    m.lock();

    if (amount++ != 0 && amount % MAX_REQUEST_COUNT == 0)
        startDownloads();

    m.unlock();
}

任何想法?谢谢!

4

0 回答 0