QT 线程池

1、建立一个新的类,且需要继承QObject和QRunnable

Class MyThreadPool : public QObject, public QRunnable{

};

注意在继承的时候,一定是QObject在前,QRunnable在后,不然会报错。

2、声明各个函数。

 

class MyThreadPool : public QObject, public QRunnable
{
    Q_OBJECT
public:
    MyThreadPool(const QString &str);
    ~MyThreadPool();

protected:
    void run();

private:
    QString str;
};

 

3、函数实现。

#include "mythreadpool.h"
#include <QDebug>

MyThreadPool::MyThreadPool(const QString &str)
{
    this->str = str;
}

MyThreadPool::~MyThreadPool()
{

}

void MyThreadPool::run()
{
    qDebug() << str;
}

4、开始使用QThreadPool。

QThreadPool tp;
tp.setMaxThreadCount(10);
tp.start(new MyThreadPool(str));

5、补充。

std::thread th(&A::getA, this);
th.detach();    //线程分离

 

posted on 2021-08-26 14:53  缘随风烬  阅读(348)  评论(0编辑  收藏  举报