2014年03月12日 星期三 09:52
QThreadPool模块提供了一个方便易用的线程池的实现,我们可以使用其start方法,传入一个QRunnable对象,来增加任务。
The QThreadPool class manages a collection of QThreads.
QThreadPool manages and recyles individual QThread objects to help reduce thread creation costs in programs that use threads. Each Qt application has one global QThreadPool object, which can be accessed by calling globalInstance().
QThreadPool deletes the QRunnable automatically by default. Use QRunnable::setAutoDelete() to change the auto-deletion flag.
示例代码如下:
#include <QCoreApplication> #include <QtCore> class Calc : public QRunnable { public: Calc():k(100),result(0){} Calc(int ik) : k(ik),result(0){} void run(){ for(int i=1;i<=k;i++){ result += i; //qDebug() << result; } } int getResult(){ return result; } private: int k; int result; }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QThreadPool pool; pool.setMaxThreadCount(10); pool.setExpiryTimeout(10000); qDebug() << pool.activeThreadCount(); auto calc=new Calc(); calc->setAutoDelete(false); auto calck=new Calc(10); calck->setAutoDelete(false); pool.start(calc); pool.start(calck); pool.waitForDone(); qDebug() << calc->getResult(); qDebug() << calck->getResult(); delete calc; delete calck; qDebug() << "Done."; return a.exec(); }
参考资料:
Zeuux © 2024
京ICP备05028076号