【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)")
相关推荐
C语言小火车14 分钟前
【C++八股文】基础知识篇
c++·tcp/ip·const·智能指针·多线程同步·static关键字·c++内存模型
liulilittle30 分钟前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
眠りたいです42 分钟前
基于脚手架微服务的视频点播系统-播放控制部分
c++·qt·ui·微服务·云原生·架构·播放器
耶啵奶膘1 小时前
uni-app头像叠加显示
开发语言·javascript·uni-app
看海天一色听风起雨落1 小时前
Python学习之装饰器
开发语言·python·学习
Want5951 小时前
C/C++圣诞树①
c语言·开发语言·c++
老赵的博客1 小时前
c++ 杂记
开发语言·c++
jimmy.hua1 小时前
[C++刷怪笼]:set/map--优质且易操作的容器
开发语言·c++
tan180°2 小时前
Boost搜索引擎 网络库与前端(4)
linux·网络·c++·搜索引擎
bkspiderx2 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法