【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)")
相关推荐
感哥2 小时前
C++ 多态
c++
沐怡旸9 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River41612 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥14 小时前
C++ std::set
c++
侃侃_天下15 小时前
最终的信号类
开发语言·c++·算法
博笙困了15 小时前
AcWing学习——差分
c++·算法
echoarts15 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix16 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
青草地溪水旁16 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁16 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式