Qt线程与线程池实现对比(QThread QThreadPool)

本文通过一个具体的Qt程序示例,介绍了如何利用Qt中的线程池来高效地处理并发任务,对比了使用线程和线程池的不同,并展示了如何设置线程池的最大线程数及超时时间。

经过四处查询,在理解了微软底层线程与线程池(转载的文章中有介绍)的基础上,终于弄明白了在Qt中的实现过程,现将代码记录如下:


#include <QCoreApplication>
#include <QThread>
#include <QTimer>
#include <QDebug>
#include <QThreadPool>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    qRegisterMetaType<string>("string");
    const string str0="5f.bmp";
    const string str1="6f.bmp";
//    QThread* thread0=new QThread;
//    QThread* thread1=new QThread;
//    thread0->start();
//    thread1->start();
//    CWorker* cworker0=new CWorker;
//    CWorker* cworker1=new CWorker;
//    cworker0->moveToThread(thread0);
//    cworker1->moveToThread(thread1);
////    QTimer* timer=new QTimer;
////    timer->start(2000);
////    QObject::connect(timer,&QTimer::timeout,[=]{
////    static int i=1;
//    cworker0->start(str0);
//    cworker1->start(str1);
////    if(++i>4)
////        timer->stop();
////    });
    //上面注释起来的部分是用线程的方式,执行多线程任务,线程数比较固定。
    //以下是线程池优势的体现
    //改变setMaxThreadCount,timer->start(1000)和count的值可以看到任务和开启线程之间的关系
    //如果多个任务到来的时间间隔比较长,那么线程池只会开启一个或少数的线程去依次执行
	//到来的任务,如果任务来的比较集中,任务间隔很短,那么线程池会开启更多线程去完成任务
    //只是最多只能开启setMaxThreadCount设置的线程数。
    QThreadPool *pThreadPool=QThreadPool::globalInstance();
    pThreadPool->setMaxThreadCount(3);
    pThreadPool->setExpiryTimeout(3000);
    qDebug()<<"main threadID:"<<QThread::currentThreadId();
    int count=3;
    QTimer* timer=new QTimer;
    timer->start(1000);
    QObject::connect(timer,&QTimer::timeout,[=]{
        static int k=0;
        string tmpStr;
        if(k%2==1)
        {
            tmpStr=str0;
        }
        else
        {
            tmpStr=str1;
        }
        CMyRunnable* MyRun=new CMyRunnable(tmpStr);
        pThreadPool->start(MyRun);
        
        if(++k==count)
            timer->stop();
    });
    return a.exec();
}

class CMyRunnable:public QRunnable
{
public:
    CMyRunnable(const string& str):QRunnable()
    {
        this->setAutoDelete(true);
        CMyStr=str;
    }
    virtual ~CMyRunnable()
    {
        qDebug()<<"over";
    }
    void run();
private:
    string CMyStr;
};
void CMyRunnable::run()
{
    process(CMyStr);//这个函数自己写,具体要在线程里完成什么任务
    qDebug()<<"threadID: "<<QThread::currentThreadId();
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SunnyFish-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值