QThreadPool

#include<QThreadPool>
#include<QDebug>

class HelloWorldTask : public QRunnable
{
public:
    void run()
    {
        qDebug() << "Hello world from thread" << QThread::currentThread();
    }
};

class MyTask : public QRunnable
{
public:
    void run()
    {
        qDebug() << "my task from thread" << QThread::currentThread();
    }
};

int main()
{
    HelloWorldTask *hello = new HelloWorldTask;
    MyTask* myTask = new MyTask;
    MyTask* myTask2 = new MyTask;
    QThreadPool* threadPool = QThreadPool::globalInstance();
    qDebug() << "active thread: " << threadPool->activeThreadCount();
    qDebug() << "expire time out: " << threadPool->expiryTimeout();
    qDebug() << "max thread count: " << threadPool->maxThreadCount();
    // QThreadPool takes ownership and deletes 'hello' automatically
    threadPool->start(hello);
    //threadPool->releaseThread();
    //threadPool->reserveThread();
    threadPool->start(myTask);
    threadPool->start(myTask2);
    if(threadPool->activeThreadCount()>0)
    {
        qDebug() << "active thread: " << threadPool->activeThreadCount();
        threadPool->waitForDone();
    }
}

active thread:  0 
expire time out:  30000 
max thread count:  2 
active thread:  2 
Hello world from thread QThread(0x93d9860) 
my task from thread QThread(0x93d9860) 
my task from thread QThread(0x93d9878) 

你可能感兴趣的:(ThreadPool)