QThreadPool类和QtConcurrent命名空间

一、QThreadPool类

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

[cpp] view plain copy
 
  1. class HelloWorldTask : public QRunnable  
  2.  {  
  3.      void run()  
  4.      {  
  5.          qDebug() << "Hello world from thread" << QThread::currentThread();  
  6.      }  
  7.  }  
  8.   
  9.  HelloWorldTask *hello = new HelloWorldTask();  
  10.  // QThreadPool takes ownership and deletes 'hello' automatically  
  11.  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包含了用于并行列表处理的函数式编程,包含实现共享内存系统的MapReduce和FilterReduce, 以及管理GUI应用程序中异步计算的类。相关的类说明如下:

QtConcurrent::map()

appliesa function to every item in aContainer, 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.

代码实例:

[cpp] view plain copy
 
  1. using namespace QtConcurrent;  
  2. void hello(QString name)  
  3. {  
  4.     qDebug() << "Hello" << name << "from" << QThread::currentThread();  
  5. }  
  6. int main(int argc, char **argv)  
  7. {  
  8.     QApplication app(argc, argv);  
  9.     QFuture<void> f1 = run(hello, QString("Alice"));  
  10.     QFuture<void> f2 = run(hello, QString("Bob"));  
  11.     f1.waitForFinished();  
  12.     f2.waitForFinished();  
  13.     return app.exec();  
  14. }  
  15. http://blog.csdn.net/fuyajun01/article/details/7075979
原文地址:https://www.cnblogs.com/lvdongjie/p/6564644.html