(Qt6 : 16-2) QThreadPool이용 QObject, QRunnable 실행

Posted by : at

Category : Qt


#include <QCoreApplication>
#include <QThreadPool>
#include <QThread>
#include "task.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QThread::currentThread()->setObjectName("Main Thread");
    qInfo() << "Starting work" << QThread::currentThread();

    qInfo() << "Max Threads" << QThreadPool::globalInstance()->maxThreadCount();

    for(int i = 0; i < 50; i++)
    {
        Task *task = new Task();
        task->setAutoDelete(true);
        QThreadPool::globalInstance()->start(task);
    }

    qInfo() << "Free to do other things" << QThread::currentThread();

    return a.exec();
}
#ifndef TASK_H
#define TASK_H

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

class Task : public QObject, public QRunnable
{
    Q_OBJECT
public:
    explicit Task(QObject *parent = nullptr);
    ~Task();

signals:

public slots:
    void run();
};

#endif // TASK_H
#include "task.h"

Task::Task(QObject *parent) : QObject(parent)
{
    qInfo() << "Constructed" << this << "on" << QThread::currentThread();
}

Task::~Task()
{
    qInfo() << "Deconstructed" << this << "on" << QThread::currentThread();
}

void Task::run()
{
    QThread *thread = QThread::currentThread();

    qInfo() << "Starting" << thread;
    for(int i = 0; i < 10; i++)
    {
        qInfo() << i << "on" << thread;
    }
    qInfo() << "Finished" << thread;
}

About Taehyung Kim

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

Star
Useful Links