美文网首页
QThreadPool

QThreadPool

作者: JiShi | 来源:发表于2017-07-31 15:57 被阅读0次

    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

    相关文章

      网友评论

          本文标题:QThreadPool

          本文链接:https://www.haomeiwen.com/subject/fddrlxtx.html