当前位置: 首页 > news >正文

【QT5 多线程示例】线程池

线程池

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

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

示例代码

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

// 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)")

相关文章:

  • Python模块与包管理完全指南
  • 时序逻辑电路
  • Linux——线程安全
  • 一文了解 MCP Server:AI 工具与外部世界的桥梁
  • ubuntu20.04安装nvidia-docker(解决有 Release 文件。 N: 无法安全地用该源进行更新,所以默认禁用该源错误)
  • ZeroMQ介绍及如何交叉编译在嵌入式Linux下使用
  • Labview信号分析系统(含报告)
  • Visual Studio2022设置默认std标准库版本
  • TCP报文格式
  • SPI协议(20250325)
  • 基于动态光影融合的缺陷实时检测和材质量化方法,并且整合EventPS、VMNer和EvDiG
  • d2025327
  • Linux下EC11旋转编码器驱动调试
  • C++入门五式——类和对象(下)
  • 【TensorRT】TensorRT从安装到推理——Python 环境下 MobileNetV4 三分类任务
  • 【AVRCP】AVRCP核心术语解析
  • LeeCode 383. 赎金信
  • 【Linux】深度解析Linux进程间通信:匿名管道原理、实战进程池与高频问题排查。
  • 05 Python 元组:不可变序列的解析和应用
  • 上位机知识篇---PythonPip安装与配置
  • 手机管理wordpress站/少儿培训
  • 有梦商城公司网站/怎么做推广网站
  • 网站web做/app拉新推广项目
  • 微信网站与响应式网站/seo教程网站优化
  • 幻灯片在什么网站做/培训心得体会1000字通用
  • 麻城网站制作公司/企业网站推广的方法