(Qt6 - Advanced) 1. QRunnable

Posted by : at

Category : Qt


  • We want multiple resuable threads
    • QTreadPool and QRunnable
// main
#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QThreadPool>
#include "counter.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QThread::currentThread()->setObjectName("Main");

    QThreadPool* pool = QThreadPool::globalInstance();
    qInfo() << pool->maxThreadCount() << "Threads";

    for(int i = 0; i < 100; i++)
    {
        Counter* c = new Counter();
        c->setAutoDelete(true);
        pool->start(c);
    }

    return a.exec();
}
// counter.h
#ifndef COUNTER_H
#define COUNTER_H

#include <QObject>
#include <QDebug>
#include <QRunnable>
#include <QThread>
#include <QRandomGenerator>

class Counter : public QRunnable
{
public:
    Counter();

    // QRunnable interface
public:
    void run();
};

#endif // COUNTER_H
// counter.cpp
#include "counter.h"

Counter::Counter()
{

}


void Counter::run()
{
    qInfo() << "Starting: " << QThread::currentThread();

    for (int i = 0; i < 20; i++) {
        //comment this out to see the threads being reused
        qInfo() << QThread::currentThread() << " = " << i;
        auto value = static_cast<unsigned long>(QRandomGenerator::global()->bounded(100));
        QThread::currentThread()->msleep(value);

    }

    qInfo() << "Finished: " << QThread::currentThread();
}

About Taehyung Kim

안녕하세요? 8년차 현업 C++ 개발자 김태형이라고 합니다. 😁 C/C++을 사랑하며 다양한 사람과의 협업을 즐깁니다. ☕ 꾸준한 자기개발을 미덕이라 생각하며 노력중이며, 제가 얻은 지식을 홈페이지에 정리 중입니다. 좀 더 상세한 제 이력서 혹은 Private 프로젝트 접근 권한을 원하신다면 메일주세요. 😎

Star
Useful Links