【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)")
相关推荐
鲨鱼吃橘子3 分钟前
HTTPS协议原理
网络·c++·网络协议·算法·http·https
一伦明悦დ35 分钟前
C++编程单例模式详细解释---模拟一个网络配置管理器,负责管理和分发网络连接参数
数据库·c++·单例模式
派阿喵搞电子37 分钟前
QT单例模式简单讲解与实现
开发语言·qt·ubuntu
牛马baby1 小时前
Java高频面试之并发编程-20
java·开发语言·面试
weixin_439723881 小时前
在bash中,如何打开特定文件,使用特定字符串替换特定字符串?请编写代码
开发语言·chrome·bash
Dxy12393102162 小时前
Python经典算法实战
开发语言·python·算法
争不过朝夕,又念着往昔2 小时前
Lua基础语法
开发语言·junit·lua
张哈大2 小时前
【 java 基础问题 第一篇 】
java·开发语言·笔记
Watink Cpper3 小时前
[Protobuf] 快速上手:安全高效的序列化指南
linux·开发语言·protobuf