QThreadPool

2017/7/29 14:03:16


QThreadPool

The QThreadPool class manages a collection of QThreads. QThreadPool manages and recycles QThread to help reduce thread creation and deconstruction costs in programs, especially in sever. As the following formula:

 #Mathjax not supported! So sad...
 cost = (create + destroy) / (create + destroy + run)

If we create the thread in a high concurrency server, the cost is unacceptable.

QThreadPool

To use one of the QThreadPool threads, subclass QRunnable and implement the run() virtual function. Then create an object of that class and pass it to QThreadPool::start().
QThreadPool deletes the QRunnable automatically by default. Use QRunnable::setAutoDelete() to change the auto-deletion flag.
Threads that are unused for a certain amount of time will expire. The default expiry timeout is 30000 milliseconds (30 seconds). This can be changed using setExpiryTimeout(). Setting a negative expiry timeout disables the expiry mechanism.

Key functions:

  • QThreadPool *QThreadPool::globalInstance(): Each Qt application has a global thread pool.
  • void QThreadPool::start(QRunnable *runnable, int priority = 0): Reserves a thread and uses it to run runnable, unless this thread will make the current thread count exceed maxThreadCount().

Example:

#include <QCoreApplication>
#include <QDebug>
#include <QRunnable>
#include <QThreadPool>
#include <QThread>

class Task : public QRunnable {
protected:
    virtual void run() {
        for ( int i = 0; i < 5; ++i ) {
            qDebug() << QThread::currentThreadId();
            QThread::msleep( 1000 );
        }
    }
};

int main( int argc, char **argv ) {
    QCoreApplication app( argc, argv );

    QThreadPool pool;
    pool.setMaxThreadCount( 3 );

    for ( int i = 0; i < 100; ++i ) {
        Task *task = new Task;
        pool.start( task );
    }

    return 0;
}

QRunnable

The QRunnable class is the base class for all runnable objects. The QRunnable class is an interface for representing a task or piece of code that needs to be executed, represented by your reimplementation of the run() function.

Key functions:

  • void QRunnable::run(): Implement this pure virtual function in your subclass.

References

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 不甘心,于是只能选择不断奋进。 很多时候,慵懒与不坚定以及其他方面的差劲成为了自己迈向未来路上的障碍。 想破也尝试...
    小林仙阅读 451评论 0 0
  • break语句 break语可用于之前介绍的循环语句和switch语。它的作用是能够立即终止整个控制流。可以根据你...
    博为峰51Code教研组阅读 1,069评论 0 0
  • ta是个什么样的APP? 网易帮你挑选优质标品购物app 优质:名品供应商(并且网易自己背书) 标品:品类较少 款...
    做个好学生阅读 532评论 0 0
  • 你有没有试过爱上一个人,放弃一切? 你有没有听过这样一句话,为爱痴狂? 你有没有想过为了他(她),放弃生命? 记得...
    鲤修缘阅读 558评论 1 3
  • 自有了工作餐后,就没有动手,晚上也懒动手,随便吃,路过超市狂了一会,见到鲜鲜的鸡内珍,买了一合,一棵西兰花...
    尘缘1227阅读 256评论 2 0