【QT5 多线程示例】线程池

线程池

【C++并发编程】(九)线程池

QThreadPoolQRunnable 是 Qt 提供的线程池管理机制。QRunnable 是一个任务抽象类;定义任务逻辑需要继承QRunnable 并实现 run() 方法。QThreadPool 负责管理线程,并将 QRunnable 任务分配到可用的线程上执行。 通过 QThreadPool::start(QRunnable *task) 提交任务,QThreadPool 会自动选择空闲线程来执行任务。

示例代码

https://github.com/BinaryAI-1024/QtStudy/tree/master/thread/threadpool

cpp 复制代码
// main.cpp
#include <QCoreApplication>
#include <QThreadPool>
#include <QRunnable>
#include <QDebug>
#include <QThread>

// 自定义任务类,继承 QRunnable
class MyTask : public QRunnable {
public:
    void run() override {
        qDebug() << "Task running on thread:" << QThread::currentThread();
        QThread::sleep(1);  // 模拟任务执行时间
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    QThreadPool *threadPool = QThreadPool::globalInstance(); // 获取全局线程池
    threadPool->setMaxThreadCount(4);  // 设置最大线程数

    for (int i = 0; i < 10; ++i) {
        MyTask *task = new MyTask();
        task->setAutoDelete(true);  // 任务完成后自动释放task指向的内存
        threadPool->start(task);
    }

    threadPool->waitForDone();  // 等待所有任务执行完毕
    return 0;
}

结果:

复制代码
Task running on thread: QThread(0xa947f68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947de8, name = "Thread (pooled)")
Task running on thread: QThread(0xa947a68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947c68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947c68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947de8, name = "Thread (pooled)")
Task running on thread: QThread(0xa947a68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947f68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947f68, name = "Thread (pooled)")
Task running on thread: QThread(0xa947c68, name = "Thread (pooled)")
相关推荐
JIngJaneIL3 分钟前
基于Java非遗传承文化管理系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot
吃西瓜的年年28 分钟前
1. 初识C语言
c语言·开发语言
mmz120732 分钟前
前缀和问题(c++)
c++·算法·图论
ULTRA??34 分钟前
初学protobuf,C++应用例子(AI辅助)
c++·python
旖旎夜光1 小时前
list实现(7)(上)
c++
CHANG_THE_WORLD1 小时前
Python 字符串全面解析
开发语言·python
不会c嘎嘎1 小时前
深入理解 C++ 异常机制:从原理到工程实践
开发语言·c++
崇山峻岭之间1 小时前
C++ Prime Plus 学习笔记026
c++·笔记·学习
永远都不秃头的程序员(互关)1 小时前
C语言 基本语法
c语言·开发语言
永远都不秃头的程序员(互关)2 小时前
Java核心技术精要:高效实践指南
java·开发语言·性能优化