经过四处查询,在理解了微软底层线程与线程池(转载的文章中有介绍)的基础上,终于弄明白了在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(); }