1. 程式人生 > >Qt 多執行緒探祕2--Qt Concurrent

Qt 多執行緒探祕2--Qt Concurrent

  很多東西存在很久但不切實使用並不能體會到它存在的深層的意義,往往這些是前人凝結出的精華而你的知識結構當前還不能體會。QFuture就是其中之一。
  Qt 多執行緒探祕1中使用QThread可以完成一個次執行緒執行的任務,雖然之需要少量的程式碼,這也是需要工作量的,要知道Qt其實早就有幫我們實現,這便是QFuture。
QFuture存在的意義應該就是能夠便於監管執行緒(通過QFutureWatcher),這方面比較簡單,不贅述,主要介紹如何實現探祕1中QThread完成的任務。於是就不得不引入QtConcurrent了(QFuture內部比較簡單,應該一般不會主動new一個QFuture出來,而是通過QtConcurrent的靜態方法產生一個QFuture,然後通過QFutureWatcher進行監控)。

  1. Concurrent Map and Map-Reduce
    QtConcurrent::map() applies a function to every item in a container, modifying the items in-place.
    QtConcurrent::mapped() is like map(), except that it returns a new container with the modifications.
    QtConcurrent::mappedReduced() is like mapped(), except that the modified results are reduced or folded into a single result.
  2. Concurrent Filter and Filter-Reduce
    QtConcurrent::filter() removes all items from a container based on the result of a filter function.
    QtConcurrent::filtered() is like filter(), except that it returns a new container with the filtered results.
    QtConcurrent::filteredReduced() is like filtered(), except that the filtered results are reduced or folded into a single result.
  3. Concurrent Run
    QtConcurrent::run() runs a function in another thread.

  主要有以上3中方法啟動一個Future,其中:
a. 1將通過map函式多執行緒地執行容器中每個元素,其中map和maped的區別在於map將修改原始容器內物件,而maped將只能從QFuture::results()獲取返回容器;最後一個mappedReduced,主要需要提供一個ReduceFunction 及QtConcurrent::ReduceOptions ,ReduceFunction 為一個合併函式,類似累加,QtConcurrent::ReduceOptions則告訴容器合併的順序為無序新增還是有序新增;
b. 2提供多執行緒的容器過濾方法,具體函式意義與a類似;
c. 3提供直接在次執行緒執行某個方法的便捷的方式(這便是我說的比QThread更便利的實現,但是這和QThread也有一個缺陷,貌似每次只能隨機指定一個執行緒,不能像QThread某個Thread代表某個固定的工作執行緒)。
上面三種方式,只有3是不能中途cancel的,其餘均可通過QFuture或者QFutureWatcher進行cancel,pause等。
QtConcurrent中還有blockingFilter等用於當前執行緒阻塞等待Future執行完成。

  餘下便是QFuture和結果相關的類

QFuture 代表非同步計算
QFutureIterator QFuture結果的迭代器
QFutureWatcher QFuture的監視器
QFutureSynchronizer 自動同步多個QFuture的幫助類