QThreadPool类和QtConcurrent命名空间

一、QThreadPool

  QThreadPool管理一组线程。它负责管理和回收单个QThread对象以减少程序中线程创建的开销。每个Qt应用程序都有一个全局的QThreadPool对象,可通过方法globalInstance()获得。为了调用QThreadPool中的一个线程,需要提供一个从QRunnable继承过来的类,并实现其中的run方法。然后创建一个该类的对象,传递给QThreadPool::start()方法。代码片断如下:

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

 HelloWorldTask *hello = new HelloWorldTask();
 // QThreadPool takes ownership and deletes 'hello' automatically
 QThreadPool::globalInstance()->start(hello);

默认情况下, QThreadPool自动删除QRunnable对象。使用QRunnable::setAutoDelete()方法可以改变该默认行为。QThreadPool支持在QRunnable::run方法中通过调用tryStart(this)来多次执行相同的QRunnable。当最后一个线程退出run函数后,如果autoDelete启用的话,将删除QRunnable对象。在autoDelete启用的情况下,调用start()方法多次执行同一QRunnable会产生竞态,就避免这样做。

  那些在一定时间内会使用的线程将会过期。默认的过期时间是30秒。可通过setExpiryTimeout()方法来设置。设置一个负数的超时值代表禁用超时机制。方法maxThreadCount()可以查询可使用的最大线程数,你也可以设置最大的线程数。activeThreadCount反应的是当前正在被使用中的线程数个数。reserveThread函数保留某个线程为外部使用,releaseThread释放该线程,这样就可以被再次使用。

二、QtConcurrent命名空间

QtConcurrent命名空间里提供了一些高级API,利用这些API可以编写多线程程序,而不用直接使用比较低级的一些类,如mutext,lock, waitcondition以及semaphore等。使用QtConcurrent命令空间的API编写的程序会根据处理器的数目自动地调整线程的个数。QtConcurrent包含了用于并行列表处理的函数式编程,包含实现共享内存系统的MapReduceFilterReduce, 以及管理GUI应用程序中异步计算的类。相关的类说明如下:

QtConcurrent::map()

appliesa function to every item in a container, modifying the itemsin-place

QtConcurrent::mapped()

islike map(), except that it returns a new container with themodifications

QtConcurrent::mappedReduced()

islike mapped(), except that the modified results are reduced orfolded into a single result.

QtConcurrent::filter()

litems from a container based on the result of a filter function.

QtConcurrent::filtered()

islike filter(), except that it returns a new container with thefiltered results

QtConcurrent::filteredReduced()

islike filtered(), except that the filtered results are reduced orfolded into a single result

QtConcurrent::run() 

runsa function in another thread.

QFutureIterator

allowsiterating through results available via QFuture.

QFutureWatcher

allowsmonitoring a QFuture usingsignals-and-slots.

QFutureSynchronizer

isa convenience class that automatically synchronizes severalQFutures.

代码实例:

using namespace QtConcurrent;
void hello(QString name)
{
    qDebug() << "Hello" << name << "from" << QThread::currentThread();
}
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QFuture<void> f1 = run(hello, QString("Alice"));
    QFuture<void> f2 = run(hello, QString("Bob"));
    f1.waitForFinished();
    f2.waitForFinished();
    return app.exec();
}


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值