一.Qt 线程池 QThreadPool介绍
二.Qt线程池的一个简单使用示例
//worker.h
#include <QDebug>
#include <QRunnable>
class Worker : public QRunnable {
public:
void run() override {
// 在这里执行线程任务
qDebug()<<"thread running!";
}
};
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QThreadPool>
#include "worker.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
// 在主线程中使用线程池
QThreadPool *pool = QThreadPool::globalInstance();
int maxThreadCount = pool->maxThreadCount(); // 获取当前线程池中的最大线程数量
pool->setMaxThreadCount(maxThreadCount); // 设置线程池的最大线程数量
// 创建任务对象
Worker *worker = new Worker;
// 将任务添加到线程池中执行
pool->start(worker);
return app.exec();
}
运行结果: