单例模式来管理QNetworkAccessManager对象的创建和销,举一个完整的http多线程例子,包括调用
时间: 2024-04-07 07:29:08 浏览: 90
下面是一个完整的使用单例模式来管理QNetworkAccessManager对象的HTTP多线程例子:
```cpp
// Singleton.h
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
QNetworkAccessManager* getNetworkAccessManager() {
if (!m_networkAccessManager) {
m_networkAccessManager = new QNetworkAccessManager(this);
}
return m_networkAccessManager;
}
private:
Singleton() {}
QNetworkAccessManager* m_networkAccessManager = nullptr;
};
// HttpWorker.h
class HttpWorker : public QObject {
Q_OBJECT
public:
HttpWorker(QNetworkAccessManager* networkAccessManager, QObject* parent = nullptr)
: QObject(parent)
, m_networkAccessManager(networkAccessManager)
{}
public slots:
void doWork(const QUrl& url) {
QNetworkRequest request(url);
QNetworkReply* reply = m_networkAccessManager->get(request);
QObject::connect(reply, &QNetworkReply::finished, [=]() {
qDebug() << reply->readAll();
reply->deleteLater();
emit finished();
});
}
signals:
void finished();
private:
QNetworkAccessManager* m_networkAccessManager = nullptr;
};
// main.cpp
#include "Singleton.h"
#include "HttpWorker.h"
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建多个HttpWorker对象,并且在不同的线程中执行
QNetworkAccessManager* networkAccessManager = Singleton::getInstance().getNetworkAccessManager();
HttpWorker worker1(networkAccessManager);
HttpWorker worker2(networkAccessManager);
QThread thread1;
QThread thread2;
worker1.moveToThread(&thread1);
worker2.moveToThread(&thread2);
QObject::connect(&thread1, &QThread::started, [&]() {
worker1.doWork(QUrl("https://www.baidu.com"));
});
QObject::connect(&thread2, &QThread::started, [&]() {
worker2.doWork(QUrl("https://www.google.com"));
});
QObject::connect(&worker1, &HttpWorker::finished, &thread1, &QThread::quit);
QObject::connect(&worker2, &HttpWorker::finished, &thread2, &QThread::quit);
QObject::connect(&thread1, &QThread::finished, &a, &QCoreApplication::quit);
QObject::connect(&thread2, &QThread::finished, &a, &QCoreApplication::quit);
thread1.start();
thread2.start();
return a.exec();
}
```
上面的代码中,首先通过Singleton::getInstance().getNetworkAccessManager()方法获取QNetworkAccessManager对象,然后在main函数中创建两个HttpWorker对象,分别在不同的线程中执行,分别发送HTTP GET请求获取百度首页和谷歌首页的内容。请求完成后,通过HttpWorker的finished信号槽和QThread的finished信号槽来退出线程,并最终调用QCoreApplication的quit()方法退出程序。
通过使用单例模式来管理QNetworkAccessManager对象的创建和销毁,避免了重复创建对象造成资源浪费和内存泄漏的问题,同时也提高了代码的可维护性和可扩展性。通过在不同的线程中执行HTTP GET请求,可以提高程序的并发处理能力,从而提高程序的性能和响应速度。
阅读全文