【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)")
相关推荐
锦***林9 分钟前
用 Python 写一个自动化办公小助手
开发语言·python·自动化
程序员老舅1 小时前
C++参数传递:值、指针与引用的原理与实战
c++·c/c++·值传递·引用传递·指针传递·参数传递机制
liu****1 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛1 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
祈祷苍天赐我java之术1 小时前
Redis 数据类型与使用场景
java·开发语言·前端·redis·分布式·spring·bootstrap
MediaTea2 小时前
Python 第三方库:matplotlib(科学绘图与数据可视化)
开发语言·python·信息可视化·matplotlib
草莓熊Lotso2 小时前
C++ 方向 Web 自动化测试入门指南:从概念到 Selenium 实战
前端·c++·python·selenium
JS.Huang2 小时前
【JavaScript】原生函数
开发语言·javascript·ecmascript
CoderCodingNo3 小时前
【GESP】C++五级考试大纲知识点梳理, (5) 算法复杂度估算(多项式、对数)
开发语言·c++·算法
星河队长3 小时前
VS创建C++动态库和C#访问过程
java·c++·c#