QThreadPool类和QtConcurrent命名空间

 

1、QThreadPool类html

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

[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释放该线程,这样就能够被再次使用。多线程

2、QtConcurrent命名空间app

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()this

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

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
相关文章
相关标签/搜索