From 96501b0a18f4f70048403dccc4cb42dd71db8f9d Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Fri, 3 Feb 2012 14:17:26 +0100 Subject: Move QtConcurrent into its own module Task-number: QTBUG-20892 Change-Id: I614500aafb6428915509983608bbb0ade4e4f016 Reviewed-by: Thiago Macieira --- src/concurrent/concurrent.pro | 59 + src/concurrent/qfuture.cpp | 697 ++++++++++++ src/concurrent/qfuture.h | 277 +++++ src/concurrent/qfutureinterface.cpp | 565 ++++++++++ src/concurrent/qfutureinterface.h | 312 ++++++ src/concurrent/qfutureinterface_p.h | 167 +++ src/concurrent/qfuturesynchronizer.cpp | 156 +++ src/concurrent/qfuturesynchronizer.h | 120 +++ src/concurrent/qfuturewatcher.cpp | 592 ++++++++++ src/concurrent/qfuturewatcher.h | 221 ++++ src/concurrent/qfuturewatcher_p.h | 90 ++ src/concurrent/qtconcurrentcompilertest.h | 78 ++ src/concurrent/qtconcurrentexception.cpp | 211 ++++ src/concurrent/qtconcurrentexception.h | 128 +++ src/concurrent/qtconcurrentfilter.cpp | 330 ++++++ src/concurrent/qtconcurrentfilter.h | 269 +++++ src/concurrent/qtconcurrentfilterkernel.h | 350 ++++++ src/concurrent/qtconcurrentfunctionwrappers.h | 303 ++++++ src/concurrent/qtconcurrentiteratekernel.cpp | 194 ++++ src/concurrent/qtconcurrentiteratekernel.h | 339 ++++++ src/concurrent/qtconcurrentmap.cpp | 402 +++++++ src/concurrent/qtconcurrentmap.h | 319 ++++++ src/concurrent/qtconcurrentmapkernel.h | 272 +++++ src/concurrent/qtconcurrentmedian.h | 129 +++ src/concurrent/qtconcurrentreducekernel.h | 254 +++++ src/concurrent/qtconcurrentresultstore.cpp | 256 +++++ src/concurrent/qtconcurrentresultstore.h | 238 ++++ src/concurrent/qtconcurrentrun.cpp | 152 +++ src/concurrent/qtconcurrentrun.h | 347 ++++++ src/concurrent/qtconcurrentrunbase.h | 154 +++ src/concurrent/qtconcurrentstoredfunctioncall.h | 1312 +++++++++++++++++++++++ src/concurrent/qtconcurrentthreadengine.cpp | 299 ++++++ src/concurrent/qtconcurrentthreadengine.h | 284 +++++ 33 files changed, 9876 insertions(+) create mode 100644 src/concurrent/concurrent.pro create mode 100644 src/concurrent/qfuture.cpp create mode 100644 src/concurrent/qfuture.h create mode 100644 src/concurrent/qfutureinterface.cpp create mode 100644 src/concurrent/qfutureinterface.h create mode 100644 src/concurrent/qfutureinterface_p.h create mode 100644 src/concurrent/qfuturesynchronizer.cpp create mode 100644 src/concurrent/qfuturesynchronizer.h create mode 100644 src/concurrent/qfuturewatcher.cpp create mode 100644 src/concurrent/qfuturewatcher.h create mode 100644 src/concurrent/qfuturewatcher_p.h create mode 100644 src/concurrent/qtconcurrentcompilertest.h create mode 100644 src/concurrent/qtconcurrentexception.cpp create mode 100644 src/concurrent/qtconcurrentexception.h create mode 100644 src/concurrent/qtconcurrentfilter.cpp create mode 100644 src/concurrent/qtconcurrentfilter.h create mode 100644 src/concurrent/qtconcurrentfilterkernel.h create mode 100644 src/concurrent/qtconcurrentfunctionwrappers.h create mode 100644 src/concurrent/qtconcurrentiteratekernel.cpp create mode 100644 src/concurrent/qtconcurrentiteratekernel.h create mode 100644 src/concurrent/qtconcurrentmap.cpp create mode 100644 src/concurrent/qtconcurrentmap.h create mode 100644 src/concurrent/qtconcurrentmapkernel.h create mode 100644 src/concurrent/qtconcurrentmedian.h create mode 100644 src/concurrent/qtconcurrentreducekernel.h create mode 100644 src/concurrent/qtconcurrentresultstore.cpp create mode 100644 src/concurrent/qtconcurrentresultstore.h create mode 100644 src/concurrent/qtconcurrentrun.cpp create mode 100644 src/concurrent/qtconcurrentrun.h create mode 100644 src/concurrent/qtconcurrentrunbase.h create mode 100644 src/concurrent/qtconcurrentstoredfunctioncall.h create mode 100644 src/concurrent/qtconcurrentthreadengine.cpp create mode 100644 src/concurrent/qtconcurrentthreadengine.h (limited to 'src/concurrent') diff --git a/src/concurrent/concurrent.pro b/src/concurrent/concurrent.pro new file mode 100644 index 0000000000..a9482af057 --- /dev/null +++ b/src/concurrent/concurrent.pro @@ -0,0 +1,59 @@ +TARGET = QtConcurrent +QPRO_PWD = $$PWD +QT = core-private + +CONFIG += module +MODULE_PRI = ../modules/qt_concurrent.pri + +DEFINES += QT_BUILD_CONCURRENT_LIB QT_NO_USING_NAMESPACE +win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x66000000 + +unix|win32-g++*:QMAKE_PKGCONFIG_REQUIRES = QtCore + +load(qt_module_config) + +HEADERS += $$QT_SOURCE_TREE/src/xml/qtconcurrentversion.h + +PRECOMPILED_HEADER = ../corelib/global/qt_pch.h + +SOURCES += \ + qfuture.cpp \ + qfutureinterface.cpp \ + qfuturesynchronizer.cpp \ + qfuturewatcher.cpp \ + qtconcurrentfilter.cpp \ + qtconcurrentmap.cpp \ + qtconcurrentresultstore.cpp \ + qtconcurrentthreadengine.cpp \ + qtconcurrentiteratekernel.cpp \ + qtconcurrentexception.cpp + +HEADERS += \ + qfuture.h \ + qfutureinterface.h \ + qfuturesynchronizer.h \ + qfuturewatcher.h \ + qtconcurrentcompilertest.h \ + qtconcurrentexception.h \ + qtconcurrentfilter.h \ + qtconcurrentfilterkernel.h \ + qtconcurrentfunctionwrappers.h \ + qtconcurrentiteratekernel.h \ + qtconcurrentmap.h \ + qtconcurrentmapkernel.h \ + qtconcurrentmedian.h \ + qtconcurrentreducekernel.h \ + qtconcurrentresultstore.h \ + qtconcurrentrun.h \ + qtconcurrentrunbase.h \ + qtconcurrentstoredfunctioncall.h \ + qtconcurrentthreadengine.h + +# private headers +HEADERS += \ + qfutureinterface_p.h \ + qfuturewatcher_p.h + +contains(QT_CONFIG, clock-gettime) { + linux-*|hpux-*|solaris-*:LIBS *= -lrt +} diff --git a/src/concurrent/qfuture.cpp b/src/concurrent/qfuture.cpp new file mode 100644 index 0000000000..9805454cb2 --- /dev/null +++ b/src/concurrent/qfuture.cpp @@ -0,0 +1,697 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! \class QFuture + \threadsafe + \brief The QFuture class represents the result of an asynchronous computation. + \since 4.4 + + \ingroup thread + + To start a computation, use one of the APIs in the + \l {Concurrent Programming}{Qt Concurrent} framework. + + QFuture allows threads to be synchronized against one or more results + which will be ready at a later point in time. The result can be of any type + that has a default constructor and a copy constructor. If a result is not + available at the time of calling the result(), resultAt(), or results() + functions, QFuture will wait until the result becomes available. You can + use the isResultReadyAt() function to determine if a result is ready or + not. For QFuture objects that report more than one result, the + resultCount() function returns the number of continuous results. This + means that it is always safe to iterate through the results from 0 to + resultCount(). + + QFuture provides a \l{Java-style iterators}{Java-style iterator} + (QFutureIterator) and an \l{STL-style iterators}{STL-style iterator} + (QFuture::const_iterator). Using these iterators is another way to access + results in the future. + + QFuture also offers ways to interact with a runnning computation. For + instance, the computation can be canceled with the cancel() function. To + pause the computation, use the setPaused() function or one of the pause(), + resume(), or togglePaused() convenience functions. Be aware that not all + asynchronous computations can be canceled or paused. For example, the + future returned by QtConcurrent::run() cannot be canceled; but the + future returned by QtConcurrent::mappedReduced() can. + + Progress information is provided by the progressValue(), + progressMinimum(), progressMaximum(), and progressText() functions. The + waitForFinished() function causes the calling thread to block and wait for + the computation to finish, ensuring that all results are available. + + The state of the computation represented by a QFuture can be queried using + the isCanceled(), isStarted(), isFinished(), isRunning(), or isPaused() + functions. + + QFuture is a lightweight reference counted class that can be passed by + value. + + QFuture is specialized to not contain any of the result fetching + functions. Any QFuture can be assigned or copied into a QFuture + as well. This is useful if only status or progress information is needed + - not the actual result data. + + To interact with running tasks using signals and slots, use QFutureWatcher. + + \sa QFutureWatcher, {Concurrent Programming}{Qt Concurrent} +*/ + +/*! \fn QFuture::QFuture() + + Constructs an empty future. +*/ + +/*! \fn QFuture::QFuture(const QFuture &other) + + Constructs a copy of \a other. + + \sa operator=() +*/ + +/*! \fn QFuture::QFuture(QFutureInterface *resultHolder) + \internal +*/ + +/*! \fn QFuture::~QFuture() + + Destroys the future. + + Note that this neither waits nor cancels the asynchronous computation. Use + waitForFinished() or QFutureSynchronizer when you need to ensure that the + computation is completed before the future is destroyed. +*/ + +/*! \fn QFuture &QFuture::operator=(const QFuture &other) + + Assigns \a other to this future and returns a reference to this future. +*/ + +/*! \fn bool QFuture::operator==(const QFuture &other) const + + Returns true if \a other is a copy of this future; otherwise returns false. +*/ + +/*! \fn bool QFuture::operator!=(const QFuture &other) const + + Returns true if \a other is \e not a copy of this future; otherwise returns + false. +*/ + +/*! \fn void QFuture::cancel() + + Cancels the asynchronous computation represented by this future. Note that + the cancelation is asynchronous. Use waitForFinished() after calling + cancel() when you need synchronous cancelation. + + Results currently available may still be accessed on a canceled future, + but new results will \e not become available after calling this function. + Any QFutureWatcher object that is watching this future will not deliver + progress and result ready signals on a canceled future. + + Be aware that not all asynchronous computations can be canceled. For + example, the future returned by QtConcurrent::run() cannot be canceled; + but the future returned by QtConcurrent::mappedReduced() can. +*/ + +/*! \fn bool QFuture::isCanceled() const + + Returns true if the asynchronous computation has been canceled with the + cancel() function; otherwise returns false. + + Be aware that the computation may still be running even though this + function returns true. See cancel() for more details. +*/ + +/*! \fn void QFuture::setPaused(bool paused) + + If \a paused is true, this function pauses the asynchronous computation + represented by the future. If the computation is already paused, this + function does nothing. Any QFutureWatcher object that is watching this + future will stop delivering progress and result ready signals while the + future is paused. Signal delivery will continue once the future is + resumed. + + If \a paused is false, this function resumes the asynchronous computation. + If the computation was not previously paused, this function does nothing. + + Be aware that not all computations can be paused. For example, the future + returned by QtConcurrent::run() cannot be paused; but the future returned + by QtConcurrent::mappedReduced() can. + + \sa pause(), resume(), togglePaused() +*/ + +/*! \fn bool QFuture::isPaused() const + + Returns true if the asynchronous computation has been paused with the + pause() function; otherwise returns false. + + Be aware that the computation may still be running even though this + function returns true. See setPaused() for more details. + + \sa setPaused(), togglePaused() +*/ + +/*! \fn void QFuture::pause() + + Pauses the asynchronous computation represented by this future. This is a + convenience method that simply calls setPaused(true). + + \sa resume() +*/ + +/*! \fn void QFuture::resume() + + Resumes the asynchronous computation represented by this future. This is a + convenience method that simply calls setPaused(false). + + \sa pause() +*/ + +/*! \fn void QFuture::togglePaused() + + Toggles the paused state of the asynchronous computation. In other words, + if the computation is currently paused, calling this function resumes it; + if the computation is running, it is paused. This is a convenience method + for calling setPaused(!isPaused()). + + \sa setPaused(), pause(), resume() +*/ + +/*! \fn bool QFuture::isStarted() const + + Returns true if the asynchronous computation represented by this future + has been started; otherwise returns false. +*/ + +/*! \fn bool QFuture::isFinished() const + + Returns true if the asynchronous computation represented by this future + has finished; otherwise returns false. +*/ + +/*! \fn bool QFuture::isRunning() const + + Returns true if the asynchronous computation represented by this future is + currently running; otherwise returns false. +*/ + +/*! \fn int QFuture::resultCount() const + + Returns the number of continuous results available in this future. The real + number of results stored might be different from this value, due to gaps + in the result set. It is always safe to iterate through the results from 0 + to resultCount(). + \sa result(), resultAt(), results() +*/ + +/*! \fn int QFuture::progressValue() const + + Returns the current progress value, which is between the progressMinimum() + and progressMaximum(). + + \sa progressMinimum(), progressMaximum() +*/ + +/*! \fn int QFuture::progressMinimum() const + + Returns the minimum progressValue(). + + \sa progressValue(), progressMaximum() +*/ + +/*! \fn int QFuture::progressMaximum() const + + Returns the maximum progressValue(). + + \sa progressValue(), progressMinimum() +*/ + +/*! \fn QString QFuture::progressText() const + + Returns the (optional) textual representation of the progress as reported + by the asynchronous computation. + + Be aware that not all computations provide a textual representation of the + progress, and as such, this function may return an empty string. +*/ + +/*! \fn void QFuture::waitForFinished() + + Waits for the asynchronous computation to finish (including cancel()ed + computations). +*/ + +/*! \fn T QFuture::result() const + + Returns the first result in the future. If the result is not immediately + available, this function will block and wait for the result to become + available. This is a convenience method for calling resultAt(0). + + \sa resultAt(), results() +*/ + +/*! \fn T QFuture::resultAt(int index) const + + Returns the result at \a index in the future. If the result is not + immediately available, this function will block and wait for the result to + become available. + + \sa result(), results(), resultCount() +*/ + +/*! \fn bool QFuture::isResultReadyAt(int index) const + + Returns true if the result at \a index is immediately available; otherwise + returns false. + + \sa resultAt(), resultCount() +*/ + +/*! \fn QFuture::operator T() const + + Returns the first result in the future. If the result is not immediately + available, this function will block and wait for the result to become + available. This is a convenience method for calling result() or + resultAt(0). + + \sa result(), resultAt(), results() +*/ + +/*! \fn QList QFuture::results() const + + Returns all results from the future. If the results are not immediately + available, this function will block and wait for them to become available. + + \sa result(), resultAt(), resultCount() +*/ + +/*! \fn QFuture::const_iterator QFuture::begin() const + + Returns a const \l{STL-style iterator} pointing to the first result in the + future. + + \sa constBegin(), end() +*/ + +/*! \fn QFuture::const_iterator QFuture::end() const + + Returns a const \l{STL-style iterator} pointing to the imaginary result + after the last result in the future. + + \sa begin(), constEnd() +*/ + +/*! \fn QFuture::const_iterator QFuture::constBegin() const + + Returns a const \l{STL-style iterator} pointing to the first result in the + future. + + \sa begin(), constEnd() +*/ + +/*! \fn QFuture::const_iterator QFuture::constEnd() const + + Returns a const \l{STL-style iterator} pointing to the imaginary result + after the last result in the future. + + \sa constBegin(), end() +*/ + +/*! \class QFuture::const_iterator + \reentrant + \since 4.4 + + \brief The QFuture::const_iterator class provides an STL-style const + iterator for QFuture. + + QFuture provides both \l{STL-style iterators} and \l{Java-style iterators}. + The STL-style iterators are more low-level and more cumbersome to use; on + the other hand, they are slightly faster and, for developers who already + know STL, have the advantage of familiarity. + + The default QFuture::const_iterator constructor creates an uninitialized + iterator. You must initialize it using a QFuture function like + QFuture::constBegin() or QFuture::constEnd() before you start iterating. + Here's a typical loop that prints all the results available in a future: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qfuture.cpp 0 + + \sa QFutureIterator, QFuture +*/ + +/*! \typedef QFuture::const_iterator::iterator_category + + Typedef for std::bidirectional_iterator_tag. Provided for STL compatibility. +*/ + +/*! \typedef QFuture::const_iterator::difference_type + + Typedef for ptrdiff_t. Provided for STL compatibility. +*/ + +/*! \typedef QFuture::const_iterator::value_type + + Typedef for T. Provided for STL compatibility. +*/ + +/*! \typedef QFuture::const_iterator::pointer + + Typedef for const T *. Provided for STL compatibility. +*/ + +/*! \typedef QFuture::const_iterator::reference + + Typedef for const T &. Provided for STL compatibility. +*/ + +/*! \fn QFuture::const_iterator::const_iterator() + + Constructs an uninitialized iterator. + + Functions like operator*() and operator++() should not be called on an + uninitialized iterartor. Use operator=() to assign a value to it before + using it. + + \sa QFuture::constBegin() QFuture::constEnd() +*/ + +/*! \fn QFuture::const_iterator::const_iterator(QFuture const * const future, int index) + \internal +*/ + +/*! \fn QFuture::const_iterator::const_iterator(const const_iterator &other) + + Constructs a copy of \a other. +*/ + +/*! \fn QFuture::const_iterator &QFuture::const_iterator::operator=(const const_iterator &other) + + Assigns \a other to this iterator. +*/ + +/*! \fn const T &QFuture::const_iterator::operator*() const + + Returns the current result. +*/ + +/*! \fn const T *QFuture::const_iterator::operator->() const + + Returns a pointer to the current result. +*/ + +/*! \fn bool QFuture::const_iterator::operator!=(const const_iterator &other) const + + Returns true if \a other points to a different result than this iterator; + otherwise returns false. + + \sa operator==() +*/ + +/*! \fn bool QFuture::const_iterator::operator==(const const_iterator &other) const + + Returns true if \a other points to the same result as this iterator; + otherwise returns false. + + \sa operator!=() +*/ + +/*! \fn QFuture::const_iterator &QFuture::const_iterator::operator++() + + The prefix ++ operator (\c{++it}) advances the iterator to the next result + in the future and returns an iterator to the new current result. + + Calling this function on QFuture::constEnd() leads to undefined results. + + \sa operator--() +*/ + +/*! \fn QFuture::const_iterator QFuture::const_iterator::operator++(int) + + \overload + + The postfix ++ operator (\c{it++}) advances the iterator to the next + result in the future and returns an iterator to the previously current + result. +*/ + +/*! \fn QFuture::const_iterator &QFuture::const_iterator::operator--() + + The prefix -- operator (\c{--it}) makes the preceding result current and + returns an iterator to the new current result. + + Calling this function on QFuture::constBegin() leads to undefined results. + + \sa operator++() +*/ + +/*! \fn QFuture::const_iterator QFuture::const_iterator::operator--(int) + + \overload + + The postfix -- operator (\c{it--}) makes the preceding result current and + returns an iterator to the previously current result. +*/ + +/*! \fn QFuture::const_iterator &QFuture::const_iterator::operator+=(int j) + + Advances the iterator by \a j results. (If \a j is negative, the iterator + goes backward.) + + \sa operator-=(), operator+() +*/ + +/*! \fn QFuture::const_iterator &QFuture::const_iterator::operator-=(int j) + + Makes the iterator go back by \a j results. (If \a j is negative, the + iterator goes forward.) + + \sa operator+=(), operator-() +*/ + +/*! \fn QFuture::const_iterator QFuture::const_iterator::operator+(int j) const + + Returns an iterator to the results at \a j positions forward from this + iterator. (If \a j is negative, the iterator goes backward.) + + \sa operator-(), operator+=() +*/ + +/*! \fn QFuture::const_iterator QFuture::const_iterator::operator-(int j) const + + Returns an iterator to the result at \a j positions backward from this + iterator. (If \a j is negative, the iterator goes forward.) + + \sa operator+(), operator-=() +*/ + +/*! \typedef QFuture::ConstIterator + + Qt-style synonym for QFuture::const_iterator. +*/ + +/*! + \class QFutureIterator + \reentrant + \since 4.4 + \inmodule QtCore + + \brief The QFutureIterator class provides a Java-style const iterator for + QFuture. + + QFuture has both \l{Java-style iterators} and \l{STL-style iterators}. The + Java-style iterators are more high-level and easier to use than the + STL-style iterators; on the other hand, they are slightly less efficient. + + An alternative to using iterators is to use index positions. Some QFuture + member functions take an index as their first parameter, making it + possible to access results without using iterators. + + QFutureIterator\ allows you to iterate over a QFuture\. Note that + there is no mutable iterator for QFuture (unlike the other Java-style + iterators). + + The QFutureIterator constructor takes a QFuture as its argument. After + construction, the iterator is located at the very beginning of the result + list (i.e. before the first result). Here's how to iterate over all the + results sequentially: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qfuture.cpp 1 + + The next() function returns the next result (waiting for it to become + available, if necessary) from the future and advances the iterator. Unlike + STL-style iterators, Java-style iterators point \e between results rather + than directly \e at results. The first call to next() advances the iterator + to the position between the first and second result, and returns the first + result; the second call to next() advances the iterator to the position + between the second and third result, and returns the second result; and + so on. + + \img javaiterators1.png + + Here's how to iterate over the elements in reverse order: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qfuture.cpp 2 + + If you want to find all occurrences of a particular value, use findNext() + or findPrevious() in a loop. + + Multiple iterators can be used on the same future. If the future is + modified while a QFutureIterator is active, the QFutureIterator will + continue iterating over the original future, ignoring the modified copy. + + \sa QFuture::const_iterator, QFuture +*/ + +/*! + \fn QFutureIterator::QFutureIterator(const QFuture &future) + + Constructs an iterator for traversing \a future. The iterator is set to be + at the front of the result list (before the first result). + + \sa operator=() +*/ + +/*! \fn QFutureIterator &QFutureIterator::operator=(const QFuture &future) + + Makes the iterator operate on \a future. The iterator is set to be at the + front of the result list (before the first result). + + \sa toFront(), toBack() +*/ + +/*! \fn void QFutureIterator::toFront() + + Moves the iterator to the front of the result list (before the first + result). + + \sa toBack(), next() +*/ + +/*! \fn void QFutureIterator::toBack() + + Moves the iterator to the back of the result list (after the last result). + + \sa toFront(), previous() +*/ + +/*! \fn bool QFutureIterator::hasNext() const + + Returns true if there is at least one result ahead of the iterator, e.g., + the iterator is \e not at the back of the result list; otherwise returns + false. + + \sa hasPrevious(), next() +*/ + +/*! \fn const T &QFutureIterator::next() + + Returns the next result and advances the iterator by one position. + + Calling this function on an iterator located at the back of the result + list leads to undefined results. + + \sa hasNext(), peekNext(), previous() +*/ + +/*! \fn const T &QFutureIterator::peekNext() const + + Returns the next result without moving the iterator. + + Calling this function on an iterator located at the back of the result + list leads to undefined results. + + \sa hasNext(), next(), peekPrevious() +*/ + +/*! \fn bool QFutureIterator::hasPrevious() const + + Returns true if there is at least one result ahead of the iterator, e.g., + the iterator is \e not at the front of the result list; otherwise returns + false. + + \sa hasNext(), previous() +*/ + +/*! \fn const T &QFutureIterator::previous() + + Returns the previous result and moves the iterator back by one position. + + Calling this function on an iterator located at the front of the result + list leads to undefined results. + + \sa hasPrevious(), peekPrevious(), next() +*/ + +/*! \fn const T &QFutureIterator::peekPrevious() const + + Returns the previous result without moving the iterator. + + Calling this function on an iterator located at the front of the result + list leads to undefined results. + + \sa hasPrevious(), previous(), peekNext() +*/ + +/*! \fn bool QFutureIterator::findNext(const T &value) + + Searches for \a value starting from the current iterator position forward. + Returns true if \a value is found; otherwise returns false. + + After the call, if \a value was found, the iterator is positioned just + after the matching result; otherwise, the iterator is positioned at the + back of the result list. + + \sa findPrevious() +*/ + +/*! \fn bool QFutureIterator::findPrevious(const T &value) + + Searches for \a value starting from the current iterator position + backward. Returns true if \a value is found; otherwise returns false. + + After the call, if \a value was found, the iterator is positioned just + before the matching result; otherwise, the iterator is positioned at the + front of the result list. + + \sa findNext() +*/ diff --git a/src/concurrent/qfuture.h b/src/concurrent/qfuture.h new file mode 100644 index 0000000000..6e99a6068e --- /dev/null +++ b/src/concurrent/qfuture.h @@ -0,0 +1,277 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFUTURE_H +#define QFUTURE_H + +#include + +#ifndef QT_NO_QFUTURE + +#include +#include +#include + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +template +class QFutureWatcher; +template <> +class QFutureWatcher; + +template +class QFuture +{ +public: + QFuture() + : d(QFutureInterface::canceledResult()) + { } + explicit QFuture(QFutureInterface *p) // internal + : d(*p) + { } + QFuture(const QFuture &other) + : d(other.d) + { } + ~QFuture() + { } + + inline QFuture &operator=(const QFuture &other); + bool operator==(const QFuture &other) const { return (d == other.d); } + bool operator!=(const QFuture &other) const { return (d != other.d); } + + void cancel() { d.cancel(); } + bool isCanceled() const { return d.isCanceled(); } + + void setPaused(bool paused) { d.setPaused(paused); } + bool isPaused() const { return d.isPaused(); } + void pause() { setPaused(true); } + void resume() { setPaused(false); } + void togglePaused() { d.togglePaused(); } + + bool isStarted() const { return d.isStarted(); } + bool isFinished() const { return d.isFinished(); } + bool isRunning() const { return d.isRunning(); } + + int resultCount() const { return d.resultCount(); } + int progressValue() const { return d.progressValue(); } + int progressMinimum() const { return d.progressMinimum(); } + int progressMaximum() const { return d.progressMaximum(); } + QString progressText() const { return d.progressText(); } + void waitForFinished() { d.waitForFinished(); } + + inline T result() const; + inline T resultAt(int index) const; + bool isResultReadyAt(int resultIndex) const { return d.isResultReadyAt(resultIndex); } + + operator T() const { return result(); } + QList results() const { return d.results(); } + + class const_iterator + { + public: + typedef std::bidirectional_iterator_tag iterator_category; + typedef qptrdiff difference_type; + typedef T value_type; + typedef const T *pointer; + typedef const T &reference; + + inline const_iterator() {} + inline const_iterator(QFuture const * const _future, int _index) : future(_future), index(_index) {} + inline const_iterator(const const_iterator &o) : future(o.future), index(o.index) {} + inline const_iterator &operator=(const const_iterator &o) + { future = o.future; index = o.index; return *this; } + inline const T &operator*() const { return future->d.resultReference(index); } + inline const T *operator->() const { return future->d.resultPointer(index); } + + inline bool operator!=(const const_iterator &other) const + { + if (index == -1 && other.index == -1) // comparing end != end? + return false; + if (other.index == -1) + return (future->isRunning() || (index < future->resultCount())); + return (index != other.index); + } + + inline bool operator==(const const_iterator &o) const { return !operator!=(o); } + inline const_iterator &operator++() { ++index; return *this; } + inline const_iterator operator++(int) { const_iterator r = *this; ++index; return r; } + inline const_iterator &operator--() { --index; return *this; } + inline const_iterator operator--(int) { const_iterator r = *this; --index; return r; } + inline const_iterator operator+(int j) const { return const_iterator(future, index + j); } + inline const_iterator operator-(int j) const { return const_iterator(future, index - j); } + inline const_iterator &operator+=(int j) { index += j; return *this; } + inline const_iterator &operator-=(int j) { index -= j; return *this; } + private: + QFuture const * future; + int index; + }; + friend class const_iterator; + typedef const_iterator ConstIterator; + + const_iterator begin() const { return const_iterator(this, 0); } + const_iterator constBegin() const { return const_iterator(this, 0); } + const_iterator end() const { return const_iterator(this, -1); } + const_iterator constEnd() const { return const_iterator(this, -1); } + +private: + friend class QFutureWatcher; + +public: // Warning: the d pointer is not documented and is considered private. + mutable QFutureInterface d; +}; + +template +inline QFuture &QFuture::operator=(const QFuture &other) +{ + d = other.d; + return *this; +} + +template +inline T QFuture::result() const +{ + d.waitForResult(0); + return d.resultReference(0); +} + +template +inline T QFuture::resultAt(int index) const +{ + d.waitForResult(index); + return d.resultReference(index); +} + +template +inline QFuture QFutureInterface::future() +{ + return QFuture(this); +} + +Q_DECLARE_SEQUENTIAL_ITERATOR(Future) + +template <> +class QFuture +{ +public: + QFuture() + : d(QFutureInterface::canceledResult()) + { } + explicit QFuture(QFutureInterfaceBase *p) // internal + : d(*p) + { } + QFuture(const QFuture &other) + : d(other.d) + { } + ~QFuture() + { } + + QFuture &operator=(const QFuture &other); + bool operator==(const QFuture &other) const { return (d == other.d); } + bool operator!=(const QFuture &other) const { return (d != other.d); } + +#if !defined(Q_CC_XLC) + template + QFuture(const QFuture &other) + : d(other.d) + { } + + template + QFuture &operator=(const QFuture &other) + { + d = other.d; + return *this; + } +#endif + + void cancel() { d.cancel(); } + bool isCanceled() const { return d.isCanceled(); } + + void setPaused(bool paused) { d.setPaused(paused); } + bool isPaused() const { return d.isPaused(); } + void pause() { setPaused(true); } + void resume() { setPaused(false); } + void togglePaused() { d.togglePaused(); } + + bool isStarted() const { return d.isStarted(); } + bool isFinished() const { return d.isFinished(); } + bool isRunning() const { return d.isRunning(); } + + int resultCount() const { return d.resultCount(); } + int progressValue() const { return d.progressValue(); } + int progressMinimum() const { return d.progressMinimum(); } + int progressMaximum() const { return d.progressMaximum(); } + QString progressText() const { return d.progressText(); } + void waitForFinished() { d.waitForFinished(); } + +private: + friend class QFutureWatcher; + +#ifdef QFUTURE_TEST +public: +#endif + mutable QFutureInterfaceBase d; +}; + +inline QFuture &QFuture::operator=(const QFuture &other) +{ + d = other.d; + return *this; +} + +inline QFuture QFutureInterface::future() +{ + return QFuture(this); +} + +template +QFuture qToVoidFuture(const QFuture &future) +{ + return QFuture(future.d); +} + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif // QFUTURE_H diff --git a/src/concurrent/qfutureinterface.cpp b/src/concurrent/qfutureinterface.cpp new file mode 100644 index 0000000000..9a273a1076 --- /dev/null +++ b/src/concurrent/qfutureinterface.cpp @@ -0,0 +1,565 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// qfutureinterface.h included from qfuture.h +#include "qfuture.h" + +#ifndef QT_NO_QFUTURE + +#include +#include +#include +#include + +#include "qfutureinterface_p.h" + +QT_BEGIN_NAMESPACE + +enum { + MaxProgressEmitsPerSecond = 25 +}; + +QFutureInterfaceBase::QFutureInterfaceBase(State initialState) + : d(new QFutureInterfaceBasePrivate(initialState)) +{ } + +QFutureInterfaceBase::QFutureInterfaceBase(const QFutureInterfaceBase &other) + : d(other.d) +{ + d->refCount.ref(); +} + +QFutureInterfaceBase::~QFutureInterfaceBase() +{ + if (!d->refCount.deref()) + delete d; +} + +void QFutureInterfaceBase::cancel() +{ + QMutexLocker locker(&d->m_mutex); + if (d->state & Canceled) + return; + + d->state = State((d->state & ~Paused) | Canceled); + d->waitCondition.wakeAll(); + d->pausedWaitCondition.wakeAll(); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Canceled)); +} + +void QFutureInterfaceBase::setPaused(bool paused) +{ + QMutexLocker locker(&d->m_mutex); + if (paused) { + d->state = State(d->state | Paused); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Paused)); + } else { + d->state = State(d->state & ~Paused); + d->pausedWaitCondition.wakeAll(); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Resumed)); + } +} + +void QFutureInterfaceBase::togglePaused() +{ + QMutexLocker locker(&d->m_mutex); + if (d->state & Paused) { + d->state = State(d->state & ~Paused); + d->pausedWaitCondition.wakeAll(); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Resumed)); + } else { + d->state = State(d->state | Paused); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Paused)); + } +} + +void QFutureInterfaceBase::setThrottled(bool enable) +{ + // bail out if we are not changing the state + if ((enable && (d->state & Throttled)) || (!enable && !(d->state & Throttled))) + return; + + // lock and change the state + QMutexLocker lock(&d->m_mutex); + if (enable) { + d->state = State(d->state | Throttled); + } else { + d->state = State(d->state & ~Throttled); + if (!(d->state & Paused)) + d->pausedWaitCondition.wakeAll(); + } +} + + +bool QFutureInterfaceBase::isRunning() const +{ + return queryState(Running); +} + +bool QFutureInterfaceBase::isStarted() const +{ + return queryState(Started); +} + +bool QFutureInterfaceBase::isCanceled() const +{ + return queryState(Canceled); +} + +bool QFutureInterfaceBase::isFinished() const +{ + return queryState(Finished); +} + +bool QFutureInterfaceBase::isPaused() const +{ + return queryState(Paused); +} + +bool QFutureInterfaceBase::isThrottled() const +{ + return queryState(Throttled); +} + +bool QFutureInterfaceBase::isResultReadyAt(int index) const +{ + QMutexLocker lock(&d->m_mutex); + return d->internal_isResultReadyAt(index); +} + +bool QFutureInterfaceBase::waitForNextResult() +{ + QMutexLocker lock(&d->m_mutex); + return d->internal_waitForNextResult(); +} + +void QFutureInterfaceBase::waitForResume() +{ + // return early if possible to avoid taking the mutex lock. + if ((d->state & Paused) == false || (d->state & Canceled)) + return; + + QMutexLocker lock(&d->m_mutex); + if ((d->state & Paused) == false || (d->state & Canceled)) + return; + + // decrease active thread count since this thread will wait. + QThreadPool::globalInstance()->releaseThread(); + + d->pausedWaitCondition.wait(&d->m_mutex); + + QThreadPool::globalInstance()->reserveThread(); +} + +int QFutureInterfaceBase::progressValue() const +{ + return d->m_progressValue; +} + +int QFutureInterfaceBase::progressMinimum() const +{ + return d->m_progressMinimum; +} + +int QFutureInterfaceBase::progressMaximum() const +{ + return d->m_progressMaximum; +} + +int QFutureInterfaceBase::resultCount() const +{ + QMutexLocker lock(&d->m_mutex); + return d->internal_resultCount(); +} + +QString QFutureInterfaceBase::progressText() const +{ + QMutexLocker locker(&d->m_mutex); + return d->m_progressText; +} + +bool QFutureInterfaceBase::isProgressUpdateNeeded() const +{ + QMutexLocker locker(&d->m_mutex); + return !d->progressTime.isValid() || (d->progressTime.elapsed() > (1000 / MaxProgressEmitsPerSecond)); +} + +void QFutureInterfaceBase::reportStarted() +{ + QMutexLocker locker(&d->m_mutex); + if ((d->state & Started) || (d->state & Canceled) || (d->state & Finished)) + return; + + d->setState(State(Started | Running)); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Started)); +} + +void QFutureInterfaceBase::reportCanceled() +{ + cancel(); +} + +#ifndef QT_NO_EXCEPTIONS +void QFutureInterfaceBase::reportException(const QtConcurrent::Exception &exception) +{ + QMutexLocker locker(&d->m_mutex); + if ((d->state & Canceled) || (d->state & Finished)) + return; + + d->m_exceptionStore.setException(exception); + d->state = State(d->state | Canceled); + d->waitCondition.wakeAll(); + d->pausedWaitCondition.wakeAll(); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Canceled)); +} +#endif + +void QFutureInterfaceBase::reportFinished() +{ + QMutexLocker locker(&d->m_mutex); + if (!(d->state & Finished)) { + d->state = State((d->state & ~Running) | Finished); + d->waitCondition.wakeAll(); + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Finished)); + } +} + +void QFutureInterfaceBase::setExpectedResultCount(int resultCount) +{ + if (d->manualProgress == false) + setProgressRange(0, resultCount); + d->m_expectedResultCount = resultCount; +} + +int QFutureInterfaceBase::expectedResultCount() +{ + return d->m_expectedResultCount; +} + +bool QFutureInterfaceBase::queryState(State state) const +{ + return (d->state & state); +} + +void QFutureInterfaceBase::waitForResult(int resultIndex) +{ + d->m_exceptionStore.throwPossibleException(); + + if (!(d->state & Running)) + return; + + // To avoid deadlocks and reduce the number of threads used, try to + // run the runnable in the current thread. + QThreadPool::globalInstance()->d_func()->stealRunnable(d->runnable); + + QMutexLocker lock(&d->m_mutex); + + if (!(d->state & Running)) + return; + + const int waitIndex = (resultIndex == -1) ? INT_MAX : resultIndex; + while ((d->state & Running) && d->internal_isResultReadyAt(waitIndex) == false) + d->waitCondition.wait(&d->m_mutex); + + d->m_exceptionStore.throwPossibleException(); +} + +void QFutureInterfaceBase::waitForFinished() +{ + if (d->state & Running) { + QThreadPool::globalInstance()->d_func()->stealRunnable(d->runnable); + + QMutexLocker lock(&d->m_mutex); + + while (d->state & Running) + d->waitCondition.wait(&d->m_mutex); + } + + d->m_exceptionStore.throwPossibleException(); +} + +void QFutureInterfaceBase::reportResultsReady(int beginIndex, int endIndex) +{ + if ((d->state & Canceled) || (d->state & Finished) || beginIndex == endIndex) + return; + + d->waitCondition.wakeAll(); + + if (d->manualProgress == false) { + if (d->internal_updateProgress(d->m_progressValue + endIndex - beginIndex) == false) { + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::ResultsReady, + beginIndex, + endIndex)); + return; + } + + d->sendCallOuts(QFutureCallOutEvent(QFutureCallOutEvent::Progress, + d->m_progressValue, + d->m_progressText), + QFutureCallOutEvent(QFutureCallOutEvent::ResultsReady, + beginIndex, + endIndex)); + return; + } + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::ResultsReady, beginIndex, endIndex)); +} + +void QFutureInterfaceBase::setRunnable(QRunnable *runnable) +{ + d->runnable = runnable; +} + +void QFutureInterfaceBase::setFilterMode(bool enable) +{ + QMutexLocker locker(&d->m_mutex); + resultStoreBase().setFilterMode(enable); +} + +void QFutureInterfaceBase::setProgressRange(int minimum, int maximum) +{ + QMutexLocker locker(&d->m_mutex); + d->m_progressMinimum = minimum; + d->m_progressMaximum = maximum; + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::ProgressRange, minimum, maximum)); +} + +void QFutureInterfaceBase::setProgressValue(int progressValue) +{ + setProgressValueAndText(progressValue, QString()); +} + +void QFutureInterfaceBase::setProgressValueAndText(int progressValue, + const QString &progressText) +{ + QMutexLocker locker(&d->m_mutex); + if (d->manualProgress == false) + d->manualProgress = true; + if (d->m_progressValue >= progressValue) + return; + + if ((d->state & Canceled) || (d->state & Finished)) + return; + + if (d->internal_updateProgress(progressValue, progressText)) { + d->sendCallOut(QFutureCallOutEvent(QFutureCallOutEvent::Progress, + d->m_progressValue, + d->m_progressText)); + } +} + +QMutex *QFutureInterfaceBase::mutex() const +{ + return &d->m_mutex; +} + +QtConcurrent::internal::ExceptionStore &QFutureInterfaceBase::exceptionStore() +{ + return d->m_exceptionStore; +} + +QtConcurrent::ResultStoreBase &QFutureInterfaceBase::resultStoreBase() +{ + return d->m_results; +} + +const QtConcurrent::ResultStoreBase &QFutureInterfaceBase::resultStoreBase() const +{ + return d->m_results; +} + +QFutureInterfaceBase &QFutureInterfaceBase::operator=(const QFutureInterfaceBase &other) +{ + other.d->refCount.ref(); + if (!d->refCount.deref()) + delete d; + d = other.d; + return *this; +} + +bool QFutureInterfaceBase::referenceCountIsOne() const +{ + return d->refCount.load() == 1; +} + +QFutureInterfaceBasePrivate::QFutureInterfaceBasePrivate(QFutureInterfaceBase::State initialState) + : refCount(1), m_progressValue(0), m_progressMinimum(0), m_progressMaximum(0), + state(initialState), pendingResults(0), + manualProgress(false), m_expectedResultCount(0), runnable(0) +{ + progressTime.invalidate(); +} + +int QFutureInterfaceBasePrivate::internal_resultCount() const +{ + return m_results.count(); // ### subtract canceled results. +} + +bool QFutureInterfaceBasePrivate::internal_isResultReadyAt(int index) const +{ + return (m_results.contains(index)); +} + +bool QFutureInterfaceBasePrivate::internal_waitForNextResult() +{ + if (m_results.hasNextResult()) + return true; + + while ((state & QFutureInterfaceBase::Running) && m_results.hasNextResult() == false) + waitCondition.wait(&m_mutex); + + return (!(state & QFutureInterfaceBase::Canceled) && m_results.hasNextResult()); +} + +bool QFutureInterfaceBasePrivate::internal_updateProgress(int progress, + const QString &progressText) +{ + if (m_progressValue >= progress) + return false; + + m_progressValue = progress; + m_progressText = progressText; + + if (progressTime.isValid() && m_progressValue != m_progressMaximum) // make sure the first and last steps are emitted. + if (progressTime.elapsed() < (1000 / MaxProgressEmitsPerSecond)) + return false; + + progressTime.start(); + return true; +} + +void QFutureInterfaceBasePrivate::internal_setThrottled(bool enable) +{ + // bail out if we are not changing the state + if ((enable && (state & QFutureInterfaceBase::Throttled)) + || (!enable && !(state & QFutureInterfaceBase::Throttled))) + return; + + // change the state + if (enable) { + state = QFutureInterfaceBase::State(state | QFutureInterfaceBase::Throttled); + } else { + state = QFutureInterfaceBase::State(state & ~QFutureInterfaceBase::Throttled); + if (!(state & QFutureInterfaceBase::Paused)) + pausedWaitCondition.wakeAll(); + } +} + +void QFutureInterfaceBasePrivate::sendCallOut(const QFutureCallOutEvent &callOutEvent) +{ + if (outputConnections.isEmpty()) + return; + + for (int i = 0; i < outputConnections.count(); ++i) + outputConnections.at(i)->postCallOutEvent(callOutEvent); +} + +void QFutureInterfaceBasePrivate::sendCallOuts(const QFutureCallOutEvent &callOutEvent1, + const QFutureCallOutEvent &callOutEvent2) +{ + if (outputConnections.isEmpty()) + return; + + for (int i = 0; i < outputConnections.count(); ++i) { + QFutureCallOutInterface *interface = outputConnections.at(i); + interface->postCallOutEvent(callOutEvent1); + interface->postCallOutEvent(callOutEvent2); + } +} + +// This function connects an output interface (for example a QFutureWatcher) +// to this future. While holding the lock we check the state and ready results +// and add the appropriate callouts to the queue. In order to avoid deadlocks, +// the actual callouts are made at the end while not holding the lock. +void QFutureInterfaceBasePrivate::connectOutputInterface(QFutureCallOutInterface *interface) +{ + QMutexLocker locker(&m_mutex); + + if (state & QFutureInterfaceBase::Started) { + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::Started)); + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::ProgressRange, + m_progressMinimum, + m_progressMaximum)); + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::Progress, + m_progressValue, + m_progressText)); + } + + QtConcurrent::ResultIteratorBase it = m_results.begin(); + while (it != m_results.end()) { + const int begin = it.resultIndex(); + const int end = begin + it.batchSize(); + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::ResultsReady, + begin, + end)); + it.batchedAdvance(); + } + + if (state & QFutureInterfaceBase::Paused) + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::Paused)); + + if (state & QFutureInterfaceBase::Canceled) + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::Canceled)); + + if (state & QFutureInterfaceBase::Finished) + interface->postCallOutEvent(QFutureCallOutEvent(QFutureCallOutEvent::Finished)); + + outputConnections.append(interface); +} + +void QFutureInterfaceBasePrivate::disconnectOutputInterface(QFutureCallOutInterface *interface) +{ + QMutexLocker lock(&m_mutex); + const int index = outputConnections.indexOf(interface); + if (index == -1) + return; + outputConnections.removeAt(index); + + interface->callOutInterfaceDisconnected(); +} + +void QFutureInterfaceBasePrivate::setState(QFutureInterfaceBase::State newState) +{ + state = newState; +} + +QT_END_NAMESPACE + +#endif // QT_NO_CONCURRENT diff --git a/src/concurrent/qfutureinterface.h b/src/concurrent/qfutureinterface.h new file mode 100644 index 0000000000..f64623ae58 --- /dev/null +++ b/src/concurrent/qfutureinterface.h @@ -0,0 +1,312 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFUTUREINTERFACE_H +#define QFUTUREINTERFACE_H + +#include +#include + +#ifndef QT_NO_QFUTURE + +#include +#include +#include + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +template class QFuture; +class QFutureInterfaceBasePrivate; +class QFutureWatcherBase; +class QFutureWatcherBasePrivate; + +class Q_CORE_EXPORT QFutureInterfaceBase +{ +public: + enum State { + NoState = 0x00, + Running = 0x01, + Started = 0x02, + Finished = 0x04, + Canceled = 0x08, + Paused = 0x10, + Throttled = 0x20 + }; + + QFutureInterfaceBase(State initialState = NoState); + QFutureInterfaceBase(const QFutureInterfaceBase &other); + virtual ~QFutureInterfaceBase(); + + // reporting functions available to the engine author: + void reportStarted(); + void reportFinished(); + void reportCanceled(); +#ifndef QT_NO_EXCEPTIONS + void reportException(const QtConcurrent::Exception &e); +#endif + void reportResultsReady(int beginIndex, int endIndex); + + void setRunnable(QRunnable *runnable); + void setFilterMode(bool enable); + void setProgressRange(int minimum, int maximum); + int progressMinimum() const; + int progressMaximum() const; + bool isProgressUpdateNeeded() const; + void setProgressValue(int progressValue); + int progressValue() const; + void setProgressValueAndText(int progressValue, const QString &progressText); + QString progressText() const; + + void setExpectedResultCount(int resultCount); + int expectedResultCount(); + int resultCount() const; + + bool queryState(State state) const; + bool isRunning() const; + bool isStarted() const; + bool isCanceled() const; + bool isFinished() const; + bool isPaused() const; + bool isThrottled() const; + bool isResultReadyAt(int index) const; + + void cancel(); + void setPaused(bool paused); + void togglePaused(); + void setThrottled(bool enable); + + void waitForFinished(); + bool waitForNextResult(); + void waitForResult(int resultIndex); + void waitForResume(); + + QMutex *mutex() const; + QtConcurrent::internal::ExceptionStore &exceptionStore(); + QtConcurrent::ResultStoreBase &resultStoreBase(); + const QtConcurrent::ResultStoreBase &resultStoreBase() const; + + inline bool operator==(const QFutureInterfaceBase &other) const { return d == other.d; } + inline bool operator!=(const QFutureInterfaceBase &other) const { return d != other.d; } + QFutureInterfaceBase &operator=(const QFutureInterfaceBase &other); + +protected: + bool referenceCountIsOne() const; +public: + +#ifndef QFUTURE_TEST +private: +#endif + QFutureInterfaceBasePrivate *d; + +private: + friend class QFutureWatcherBase; + friend class QFutureWatcherBasePrivate; +}; + +template +class QFutureInterface : public QFutureInterfaceBase +{ +public: + QFutureInterface(State initialState = NoState) + : QFutureInterfaceBase(initialState) + { } + QFutureInterface(const QFutureInterface &other) + : QFutureInterfaceBase(other) + { } + ~QFutureInterface() + { + if (referenceCountIsOne()) + resultStore().clear(); + } + + static QFutureInterface canceledResult() + { return QFutureInterface(State(Started | Finished | Canceled)); } + + QFutureInterface &operator=(const QFutureInterface &other) + { + if (referenceCountIsOne()) + resultStore().clear(); + QFutureInterfaceBase::operator=(other); + return *this; + } + + inline QFuture future(); // implemented in qfuture.h + + inline void reportResult(const T *result, int index = -1); + inline void reportResult(const T &result, int index = -1); + inline void reportResults(const QVector &results, int beginIndex = -1, int count = -1); + inline void reportFinished(const T *result = 0); + + inline const T &resultReference(int index) const; + inline const T *resultPointer(int index) const; + inline QList results(); +private: + QtConcurrent::ResultStore &resultStore() + { return static_cast &>(resultStoreBase()); } + const QtConcurrent::ResultStore &resultStore() const + { return static_cast &>(resultStoreBase()); } +}; + +template +inline void QFutureInterface::reportResult(const T *result, int index) +{ + QMutexLocker locker(mutex()); + if (this->queryState(Canceled) || this->queryState(Finished)) { + return; + } + + QtConcurrent::ResultStore &store = resultStore(); + + + if (store.filterMode()) { + const int resultCountBefore = store.count(); + store.addResult(index, result); + this->reportResultsReady(resultCountBefore, resultCountBefore + store.count()); + } else { + const int insertIndex = store.addResult(index, result); + this->reportResultsReady(insertIndex, insertIndex + 1); + } +} + +template +inline void QFutureInterface::reportResult(const T &result, int index) +{ + reportResult(&result, index); +} + +template +inline void QFutureInterface::reportResults(const QVector &_results, int beginIndex, int count) +{ + QMutexLocker locker(mutex()); + if (this->queryState(Canceled) || this->queryState(Finished)) { + return; + } + + QtConcurrent::ResultStore &store = resultStore(); + + if (store.filterMode()) { + const int resultCountBefore = store.count(); + store.addResults(beginIndex, &_results, count); + this->reportResultsReady(resultCountBefore, store.count()); + } else { + const int insertIndex = store.addResults(beginIndex, &_results, count); + this->reportResultsReady(insertIndex, insertIndex + _results.count()); + } +} + +template +inline void QFutureInterface::reportFinished(const T *result) +{ + if (result) + reportResult(result); + QFutureInterfaceBase::reportFinished(); +} + +template +inline const T &QFutureInterface::resultReference(int index) const +{ + QMutexLocker lock(mutex()); + return resultStore().resultAt(index).value(); +} + +template +inline const T *QFutureInterface::resultPointer(int index) const +{ + QMutexLocker lock(mutex()); + return resultStore().resultAt(index).pointer(); +} + +template +inline QList QFutureInterface::results() +{ + if (this->isCanceled()) { + exceptionStore().throwPossibleException(); + return QList(); + } + QFutureInterfaceBase::waitForResult(-1); + + QList res; + QMutexLocker lock(mutex()); + + QtConcurrent::ResultIterator it = resultStore().begin(); + while (it != resultStore().end()) { + res.append(it.value()); + ++it; + } + + return res; +} + +template <> +class QFutureInterface : public QFutureInterfaceBase +{ +public: + QFutureInterface(State initialState = NoState) + : QFutureInterfaceBase(initialState) + { } + QFutureInterface(const QFutureInterface &other) + : QFutureInterfaceBase(other) + { } + + static QFutureInterface canceledResult() + { return QFutureInterface(State(Started | Finished | Canceled)); } + + QFutureInterface &operator=(const QFutureInterface &other) + { + QFutureInterfaceBase::operator=(other); + return *this; + } + + inline QFuture future(); // implemented in qfuture.h + + void reportResult(const void *, int) { } + void reportResults(const QVector &, int) { } + void reportFinished(void * = 0) { QFutureInterfaceBase::reportFinished(); } +}; + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif // QFUTUREINTERFACE_H diff --git a/src/concurrent/qfutureinterface_p.h b/src/concurrent/qfutureinterface_p.h new file mode 100644 index 0000000000..ea52621378 --- /dev/null +++ b/src/concurrent/qfutureinterface_p.h @@ -0,0 +1,167 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFUTUREINTERFACE_P_H +#define QFUTUREINTERFACE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QFutureCallOutEvent : public QEvent +{ +public: + enum CallOutType { + Started, + Finished, + Canceled, + Paused, + Resumed, + Progress, + ProgressRange, + ResultsReady + }; + + QFutureCallOutEvent() + : QEvent(QEvent::FutureCallOut), callOutType(CallOutType(0)), index1(-1), index2(-1) + { } + QFutureCallOutEvent(CallOutType callOutType, int index1 = -1) + : QEvent(QEvent::FutureCallOut), callOutType(callOutType), index1(index1), index2(-1) + { } + QFutureCallOutEvent(CallOutType callOutType, int index1, int index2) + : QEvent(QEvent::FutureCallOut), callOutType(callOutType), index1(index1), index2(index2) + { } + + QFutureCallOutEvent(CallOutType callOutType, int index1, const QString &text) + : QEvent(QEvent::FutureCallOut), + callOutType(callOutType), + index1(index1), + index2(-1), + text(text) + { } + + CallOutType callOutType; + int index1; + int index2; + QString text; + + QFutureCallOutEvent *clone() const + { + return new QFutureCallOutEvent(callOutType, index1, index2, text); + } + +private: + QFutureCallOutEvent(CallOutType callOutType, + int index1, + int index2, + const QString &text) + : QEvent(QEvent::FutureCallOut), + callOutType(callOutType), + index1(index1), + index2(index2), + text(text) + { } +}; + +class QFutureCallOutInterface +{ +public: + virtual ~QFutureCallOutInterface() {} + virtual void postCallOutEvent(const QFutureCallOutEvent &) = 0; + virtual void callOutInterfaceDisconnected() = 0; +}; + +class QFutureInterfaceBasePrivate +{ +public: + QFutureInterfaceBasePrivate(QFutureInterfaceBase::State initialState); + + QAtomicInt refCount; + mutable QMutex m_mutex; + QWaitCondition waitCondition; + QList outputConnections; + int m_progressValue; + int m_progressMinimum; + int m_progressMaximum; + QFutureInterfaceBase::State state; + QElapsedTimer progressTime; + QWaitCondition pausedWaitCondition; + int pendingResults; + QtConcurrent::ResultStoreBase m_results; + bool manualProgress; + int m_expectedResultCount; + QtConcurrent::internal::ExceptionStore m_exceptionStore; + QString m_progressText; + QRunnable *runnable; + + // Internal functions that does not change the mutex state. + // The mutex must be locked when calling these. + int internal_resultCount() const; + bool internal_isResultReadyAt(int index) const; + bool internal_waitForNextResult(); + bool internal_updateProgress(int progress, const QString &progressText = QString()); + void internal_setThrottled(bool enable); + void sendCallOut(const QFutureCallOutEvent &callOut); + void sendCallOuts(const QFutureCallOutEvent &callOut1, const QFutureCallOutEvent &callOut2); + void connectOutputInterface(QFutureCallOutInterface *iface); + void disconnectOutputInterface(QFutureCallOutInterface *iface); + + void setState(QFutureInterfaceBase::State state); +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/concurrent/qfuturesynchronizer.cpp b/src/concurrent/qfuturesynchronizer.cpp new file mode 100644 index 0000000000..34b00daf4f --- /dev/null +++ b/src/concurrent/qfuturesynchronizer.cpp @@ -0,0 +1,156 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! \class QFutureSynchronizer + \since 4.4 + + \brief The QFutureSynchronizer class is a convenience class that simplifies + QFuture synchronization. + + \ingroup thread + + QFutureSynchronizer is a template class that simplifies synchronization of + one or more QFuture objects. Futures are added using the addFuture() or + setFuture() functions. The futures() function returns a list of futures. + Use clearFutures() to remove all futures from the QFutureSynchronizer. + + The waitForFinished() function waits for all futures to finish. + The destructor of QFutureSynchronizer calls waitForFinished(), providing + an easy way to ensure that all futures have finished before returning from + a function: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qfuturesynchronizer.cpp 0 + + The behavior of waitForFinished() can be changed using the + setCancelOnWait() function. Calling setCancelOnWait(true) will cause + waitForFinished() to cancel all futures before waiting for them to finish. + You can query the status of the cancel-on-wait feature using the + cancelOnWait() function. + + \sa QFuture, QFutureWatcher, {Concurrent Programming}{Qt Concurrent} +*/ + +/*! + \fn QFutureSynchronizer::QFutureSynchronizer() + + Constructs a QFutureSynchronizer. +*/ + +/*! + \fn QFutureSynchronizer::QFutureSynchronizer(const QFuture &future) + + Constructs a QFutureSynchronizer and begins watching \a future by calling + addFuture(). + + \sa addFuture() +*/ + +/*! + \fn QFutureSynchronizer::~QFutureSynchronizer() + + Calls waitForFinished() function to ensure that all futures have finished + before destroying this QFutureSynchronizer. + + \sa waitForFinished() +*/ + +/*! + \fn void QFutureSynchronizer::setFuture(const QFuture &future) + + Sets \a future to be the only future managed by this QFutureSynchronizer. + This is a convenience function that calls waitForFinished(), + then clearFutures(), and finally passes \a future to addFuture(). + + \sa addFuture(), waitForFinished(), clearFutures() +*/ + +/*! + \fn void QFutureSynchronizer::addFuture(const QFuture &future) + + Adds \a future to the list of managed futures. + + \sa futures() +*/ + +/*! + \fn void QFutureSynchronizer::waitForFinished() + + Waits for all futures to finish. If cancelOnWait() returns true, each + future is canceled before waiting for them to finish. + + \sa cancelOnWait(), setCancelOnWait() +*/ + +/*! + \fn void QFutureSynchronizer::clearFutures() + + Removes all managed futures from this QFutureSynchronizer. + + \sa addFuture(), setFuture() +*/ + +/*! + \fn QList > QFutureSynchronizer::futures() const + + Returns a list of all managed futures. + + \sa addFuture(), setFuture() +*/ + +/*! + \fn void QFutureSynchronizer::setCancelOnWait(bool enabled) + + Enables or disables the cancel-on-wait feature based on the \a enabled + argument. If \a enabled is true, the waitForFinished() function will cancel + all futures before waiting for them to finish. + + \sa waitForFinished() +*/ + +/*! + \fn bool QFutureSynchronizer::cancelOnWait() const + + Returns true if the cancel-on-wait feature is enabled; otherwise returns + false. If cancel-on-wait is enabled, the waitForFinished() function will + cancel all futures before waiting for them to finish. + + \sa waitForFinished() +*/ diff --git a/src/concurrent/qfuturesynchronizer.h b/src/concurrent/qfuturesynchronizer.h new file mode 100644 index 0000000000..8b7e710ea9 --- /dev/null +++ b/src/concurrent/qfuturesynchronizer.h @@ -0,0 +1,120 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFUTRUESYNCHRONIZER_H +#define QFUTRUESYNCHRONIZER_H + +#include + +#ifndef QT_NO_CONCURRENT + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +template +class QFutureSynchronizer +{ + Q_DISABLE_COPY(QFutureSynchronizer) + +public: + QFutureSynchronizer() : m_cancelOnWait(false) { } + explicit QFutureSynchronizer(const QFuture &future) + : m_cancelOnWait(false) + { addFuture(future); } + ~QFutureSynchronizer() { waitForFinished(); } + + void setFuture(const QFuture &future) + { + waitForFinished(); + m_futures.clear(); + addFuture(future); + } + + void addFuture(const QFuture &future) + { + m_futures.append(future); + } + + void waitForFinished() + { + if (m_cancelOnWait) { + for (int i = 0; i < m_futures.count(); ++i) { + m_futures[i].cancel(); + } + } + + for (int i = 0; i < m_futures.count(); ++i) { + m_futures[i].waitForFinished(); + } + } + + void clearFutures() + { + m_futures.clear(); + } + + QList > futures() const + { + return m_futures; + } + + void setCancelOnWait(bool enabled) + { + m_cancelOnWait = enabled; + } + + bool cancelOnWait() const + { + return m_cancelOnWait; + } + +protected: + QList > m_futures; + bool m_cancelOnWait; +}; + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif // QFUTRUESYNCHRONIZER_H diff --git a/src/concurrent/qfuturewatcher.cpp b/src/concurrent/qfuturewatcher.cpp new file mode 100644 index 0000000000..d3a1122a07 --- /dev/null +++ b/src/concurrent/qfuturewatcher.cpp @@ -0,0 +1,592 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qfuturewatcher.h" + +#ifndef QT_NO_QFUTURE + +#include +#include +#include + +#include "qfuturewatcher_p.h" + +QT_BEGIN_NAMESPACE + +/*! \class QFutureWatcher + \reentrant + \since 4.4 + + \ingroup thread + + \brief The QFutureWatcher class allows monitoring a QFuture using signals + and slots. + + QFutureWatcher provides information and notifications about a QFuture. Use + the setFuture() function to start watching a particular QFuture. The + future() function returns the future set with setFuture(). + + For convenience, several of QFuture's functions are also available in + QFutureWatcher: progressValue(), progressMinimum(), progressMaximum(), + progressText(), isStarted(), isFinished(), isRunning(), isCanceled(), + isPaused(), waitForFinished(), result(), and resultAt(). The cancel(), + setPaused(), pause(), resume(), and togglePaused() functions are slots in + QFutureWatcher. + + Status changes are reported via the started(), finished(), canceled(), + paused(), resumed(), resultReadyAt(), and resultsReadyAt() signals. + Progress information is provided from the progressRangeChanged(), + void progressValueChanged(), and progressTextChanged() signals. + + Throttling control is provided by the setPendingResultsLimit() function. + When the number of pending resultReadyAt() or resultsReadyAt() signals + exceeds the limit, the computation represented by the future will be + throttled automatically. The computation will resume once the number of + pending signals drops below the limit. + + Example: Starting a computation and getting a slot callback when it's + finished: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qfuturewatcher.cpp 0 + + Be aware that not all asynchronous computations can be canceled or paused. + For example, the future returned by QtConcurrent::run() cannot be + canceled; but the future returned by QtConcurrent::mappedReduced() can. + + QFutureWatcher is specialized to not contain any of the result + fetching functions. Any QFuture can be watched by a + QFutureWatcher as well. This is useful if only status or progress + information is needed; not the actual result data. + + \sa QFuture, {Concurrent Programming}{Qt Concurrent} +*/ + +/*! \fn QFutureWatcher::QFutureWatcher(QObject *parent) + + Constructs a new QFutureWatcher with the given \a parent. +*/ +QFutureWatcherBase::QFutureWatcherBase(QObject *parent) + :QObject(*new QFutureWatcherBasePrivate, parent) +{ } + +/*! \fn QFutureWatcher::~QFutureWatcher() + + Destroys the QFutureWatcher. +*/ + +/*! \fn void QFutureWatcher::cancel() + + Cancels the asynchronous computation represented by the future(). Note that + the cancelation is asynchronous. Use waitForFinished() after calling + cancel() when you need synchronous cancelation. + + Currently available results may still be accessed on a canceled QFuture, + but new results will \e not become available after calling this function. + Also, this QFutureWatcher will not deliver progress and result ready + signals once canceled. This includes the progressValueChanged(), + progressRangeChanged(), progressTextChanged(), resultReadyAt(), and + resultsReadyAt() signals. + + Be aware that not all asynchronous computations can be canceled. For + example, the QFuture returned by QtConcurrent::run() cannot be canceled; + but the QFuture returned by QtConcurrent::mappedReduced() can. +*/ +void QFutureWatcherBase::cancel() +{ + futureInterface().cancel(); +} + +/*! \fn void QFutureWatcher::setPaused(bool paused) + + If \a paused is true, this function pauses the asynchronous computation + represented by the future(). If the computation is already paused, this + function does nothing. This QFutureWatcher will stop delivering progress + and result ready signals while the future is paused. Signal delivery will + continue once the computation is resumed. + + If \a paused is false, this function resumes the asynchronous computation. + If the computation was not previously paused, this function does nothing. + + Be aware that not all computations can be paused. For example, the + QFuture returned by QtConcurrent::run() cannot be paused; but the QFuture + returned by QtConcurrent::mappedReduced() can. + + \sa pause(), resume(), togglePaused() +*/ +void QFutureWatcherBase::setPaused(bool paused) +{ + futureInterface().setPaused(paused); +} + +/*! \fn void QFutureWatcher::pause() + + Pauses the asynchronous computation represented by the future(). This is a + convenience method that simply calls setPaused(true). + + \sa resume() +*/ +void QFutureWatcherBase::pause() +{ + futureInterface().setPaused(true); +} + +/*! \fn void QFutureWatcher::resume() + + Resumes the asynchronous computation represented by the future(). This is + a convenience method that simply calls setPaused(false). + + \sa pause() +*/ +void QFutureWatcherBase::resume() +{ + futureInterface().setPaused(false); +} + +/*! \fn void QFutureWatcher::togglePaused() + + Toggles the paused state of the asynchronous computation. In other words, + if the computation is currently paused, calling this function resumes it; + if the computation is running, it becomes paused. This is a convenience + method for calling setPaused(!isPaused()). + + \sa setPaused(), pause(), resume() +*/ +void QFutureWatcherBase::togglePaused() +{ + futureInterface().togglePaused(); +} + +/*! \fn int QFutureWatcher::progressValue() const + + Returns the current progress value, which is between the progressMinimum() + and progressMaximum(). + + \sa progressMinimum(), progressMaximum() +*/ +int QFutureWatcherBase::progressValue() const +{ + return futureInterface().progressValue(); +} + +/*! \fn int QFutureWatcher::progressMinimum() const + + Returns the minimum progressValue(). + + \sa progressValue(), progressMaximum() +*/ +int QFutureWatcherBase::progressMinimum() const +{ + return futureInterface().progressMinimum(); +} + +/*! \fn int QFutureWatcher::progressMaximum() const + + Returns the maximum progressValue(). + + \sa progressValue(), progressMinimum() +*/ +int QFutureWatcherBase::progressMaximum() const +{ + return futureInterface().progressMaximum(); +} + +/*! \fn QString QFutureWatcher::progressText() const + + Returns the (optional) textual representation of the progress as reported + by the asynchronous computation. + + Be aware that not all computations provide a textual representation of the + progress, and as such, this function may return an empty string. +*/ +QString QFutureWatcherBase::progressText() const +{ + return futureInterface().progressText(); +} + +/*! \fn bool QFutureWatcher::isStarted() const + + Returns true if the asynchronous computation represented by the future() + has been started; otherwise returns false. +*/ +bool QFutureWatcherBase::isStarted() const +{ + return futureInterface().queryState(QFutureInterfaceBase::Started); +} + +/*! \fn bool QFutureWatcher::isFinished() const + + Returns true if the asynchronous computation represented by the future() + has finished; otherwise returns false. +*/ +bool QFutureWatcherBase::isFinished() const +{ + Q_D(const QFutureWatcherBase); + return d->finished; +} + +/*! \fn bool QFutureWatcher::isRunning() const + + Returns true if the asynchronous computation represented by the future() + is currently running; otherwise returns false. +*/ +bool QFutureWatcherBase::isRunning() const +{ + return futureInterface().queryState(QFutureInterfaceBase::Running); +} + +/*! \fn bool QFutureWatcher::isCanceled() const + + Returns true if the asynchronous computation has been canceled with the + cancel() function; otherwise returns false. + + Be aware that the computation may still be running even though this + function returns true. See cancel() for more details. +*/ +bool QFutureWatcherBase::isCanceled() const +{ + return futureInterface().queryState(QFutureInterfaceBase::Canceled); +} + +/*! \fn bool QFutureWatcher::isPaused() const + + Returns true if the asynchronous computation has been paused with the + pause() function; otherwise returns false. + + Be aware that the computation may still be running even though this + function returns true. See setPaused() for more details. + + \sa setPaused(), togglePaused() +*/ +bool QFutureWatcherBase::isPaused() const +{ + return futureInterface().queryState(QFutureInterfaceBase::Paused); +} + +/*! \fn void QFutureWatcher::waitForFinished() + + Waits for the asynchronous computation to finish (including cancel()ed + computations). +*/ +void QFutureWatcherBase::waitForFinished() +{ + futureInterface().waitForFinished(); +} + +/*! \fn void QFutureWatcher::setPendingResultsLimit(int limit) + + The setPendingResultsLimit() provides throttling control. When the number + of pending resultReadyAt() or resultsReadyAt() signals exceeds the + \a limit, the computation represented by the future will be throttled + automatically. The computation will resume once the number of pending + signals drops below the \a limit. +*/ + +bool QFutureWatcherBase::event(QEvent *event) +{ + Q_D(QFutureWatcherBase); + if (event->type() == QEvent::FutureCallOut) { + QFutureCallOutEvent *callOutEvent = static_cast(event); + + if (futureInterface().isPaused()) { + d->pendingCallOutEvents.append(callOutEvent->clone()); + return true; + } + + if (callOutEvent->callOutType == QFutureCallOutEvent::Resumed + && !d->pendingCallOutEvents.isEmpty()) { + // send the resume + d->sendCallOutEvent(callOutEvent); + + // next send all pending call outs + for (int i = 0; i < d->pendingCallOutEvents.count(); ++i) + d->sendCallOutEvent(d->pendingCallOutEvents.at(i)); + qDeleteAll(d->pendingCallOutEvents); + d->pendingCallOutEvents.clear(); + } else { + d->sendCallOutEvent(callOutEvent); + } + return true; + } + return QObject::event(event); +} + +void QFutureWatcherBase::setPendingResultsLimit(int limit) +{ + Q_D(QFutureWatcherBase); + d->maximumPendingResultsReady = limit; +} + +void QFutureWatcherBase::connectNotify(const char * signal) +{ + Q_D(QFutureWatcherBase); + if (qstrcmp(signal, SIGNAL(resultReadyAt(int))) == 0) + d->resultAtConnected.ref(); +#ifndef QT_NO_DEBUG + if (qstrcmp(signal, SIGNAL(finished())) == 0) { + if (futureInterface().isRunning()) { + //connections should be established before calling stFuture to avoid race. + // (The future could finish before the connection is made.) + qWarning("QFutureWatcher::connect: connecting after calling setFuture() is likely to produce race"); + } + } +#endif +} + +void QFutureWatcherBase::disconnectNotify(const char * signal) +{ + Q_D(QFutureWatcherBase); + if (qstrcmp(signal, SIGNAL(resultReadyAt(int))) == 0) + d->resultAtConnected.deref(); +} + +/*! + \internal +*/ +QFutureWatcherBasePrivate::QFutureWatcherBasePrivate() + : maximumPendingResultsReady(QThread::idealThreadCount() * 2), + resultAtConnected(0) +{ } + +/*! + \internal +*/ +void QFutureWatcherBase::connectOutputInterface() +{ + futureInterface().d->connectOutputInterface(d_func()); +} + +/*! + \internal +*/ +void QFutureWatcherBase::disconnectOutputInterface(bool pendingAssignment) +{ + if (pendingAssignment) { + Q_D(QFutureWatcherBase); + d->pendingResultsReady.store(0); + qDeleteAll(d->pendingCallOutEvents); + d->pendingCallOutEvents.clear(); + d->finished = false; + } + + futureInterface().d->disconnectOutputInterface(d_func()); +} + +void QFutureWatcherBasePrivate::postCallOutEvent(const QFutureCallOutEvent &callOutEvent) +{ + Q_Q(QFutureWatcherBase); + + if (callOutEvent.callOutType == QFutureCallOutEvent::ResultsReady) { + if (pendingResultsReady.fetchAndAddRelaxed(1) >= maximumPendingResultsReady) + q->futureInterface().d->internal_setThrottled(true); + } + + QCoreApplication::postEvent(q, callOutEvent.clone()); +} + +void QFutureWatcherBasePrivate::callOutInterfaceDisconnected() +{ + QCoreApplication::removePostedEvents(q_func(), QEvent::FutureCallOut); +} + +void QFutureWatcherBasePrivate::sendCallOutEvent(QFutureCallOutEvent *event) +{ + Q_Q(QFutureWatcherBase); + + switch (event->callOutType) { + case QFutureCallOutEvent::Started: + emit q->started(); + break; + case QFutureCallOutEvent::Finished: + finished = true; + emit q->finished(); + break; + case QFutureCallOutEvent::Canceled: + pendingResultsReady.store(0); + emit q->canceled(); + break; + case QFutureCallOutEvent::Paused: + if (q->futureInterface().isCanceled()) + break; + emit q->paused(); + break; + case QFutureCallOutEvent::Resumed: + if (q->futureInterface().isCanceled()) + break; + emit q->resumed(); + break; + case QFutureCallOutEvent::ResultsReady: { + if (q->futureInterface().isCanceled()) + break; + + if (pendingResultsReady.fetchAndAddRelaxed(-1) <= maximumPendingResultsReady) + q->futureInterface().setThrottled(false); + + const int beginIndex = event->index1; + const int endIndex = event->index2; + + emit q->resultsReadyAt(beginIndex, endIndex); + + if (resultAtConnected.load() <= 0) + break; + + for (int i = beginIndex; i < endIndex; ++i) + emit q->resultReadyAt(i); + + } break; + case QFutureCallOutEvent::Progress: + if (q->futureInterface().isCanceled()) + break; + + emit q->progressValueChanged(event->index1); + if (!event->text.isNull()) // ### + q->progressTextChanged(event->text); + break; + case QFutureCallOutEvent::ProgressRange: + emit q->progressRangeChanged(event->index1, event->index2); + break; + default: break; + } +} + + +/*! \fn const T &QFutureWatcher::result() const + + Returns the first result in the future(). If the result is not immediately + available, this function will block and wait for the result to become + available. This is a convenience method for calling resultAt(0). + + \sa resultAt() +*/ + +/*! \fn const T &QFutureWatcher::resultAt(int index) const + + Returns the result at \a index in the future(). If the result is not + immediately available, this function will block and wait for the result to + become available. + + \sa result() +*/ + +/*! \fn void QFutureWatcher::setFuture(const QFuture &future) + + Starts watching the given \a future. + + One of the signals might be emitted for the current state of the + \a future. For example, if the future is already stopped, the + finished signal will be emitted. + + To avoid a race condition, it is important to call this function + \e after doing the connections. +*/ + +/*! \fn QFuture QFutureWatcher::future() const + + Returns the watched future. +*/ + +/*! \fn void QFutureWatcher::started() + + This signal is emitted when this QFutureWatcher starts watching the future + set with setFuture(). +*/ + +/*! + \fn void QFutureWatcher::finished() + This signal is emitted when the watched future finishes. +*/ + +/*! + \fn void QFutureWatcher::canceled() + This signal is emitted if the watched future is canceled. +*/ + +/*! \fn void QFutureWatcher::paused() + This signal is emitted when the watched future is paused. +*/ + +/*! \fn void QFutureWatcher::resumed() + This signal is emitted when the watched future is resumed. +*/ + +/*! + \fn void QFutureWatcher::progressRangeChanged(int minimum, int maximum) + + The progress range for the watched future has changed to \a minimum and + \a maximum +*/ + +/*! + \fn void QFutureWatcher::progressValueChanged(int progressValue) + + This signal is emitted when the watched future reports progress, + \a progressValue gives the current progress. In order to avoid overloading + the GUI event loop, QFutureWatcher limits the progress signal emission + rate. This means that listeners connected to this slot might not get all + progress reports the future makes. The last progress update (where + \a progressValue equals the maximum value) will always be delivered. +*/ + +/*! \fn void QFutureWatcher::progressTextChanged(const QString &progressText) + + This signal is emitted when the watched future reports textual progress + information, \a progressText. +*/ + +/*! + \fn void QFutureWatcher::resultReadyAt(int index) + + This signal is emitted when the watched future reports a ready result at + \a index. If the future reports multiple results, the index will indicate + which one it is. Results can be reported out-of-order. To get the result, + call future().result(index); +*/ + +/*! + \fn void QFutureWatcher::resultsReadyAt(int beginIndex, int endIndex); + + This signal is emitted when the watched future reports ready results. + The results are indexed from \a beginIndex to \a endIndex. + +*/ + +QT_END_NAMESPACE + +#endif // QT_NO_CONCURRENT diff --git a/src/concurrent/qfuturewatcher.h b/src/concurrent/qfuturewatcher.h new file mode 100644 index 0000000000..0e94863d12 --- /dev/null +++ b/src/concurrent/qfuturewatcher.h @@ -0,0 +1,221 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFUTUREWATCHER_H +#define QFUTUREWATCHER_H + +#include + +#ifndef QT_NO_QFUTURE + +#include + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +class QEvent; + +class QFutureWatcherBasePrivate; +class Q_CORE_EXPORT QFutureWatcherBase : public QObject +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QFutureWatcherBase) + +public: + QFutureWatcherBase(QObject *parent = 0); + + int progressValue() const; + int progressMinimum() const; + int progressMaximum() const; + QString progressText() const; + + bool isStarted() const; + bool isFinished() const; + bool isRunning() const; + bool isCanceled() const; + bool isPaused() const; + + void waitForFinished(); + + void setPendingResultsLimit(int limit); + + bool event(QEvent *event); + +Q_SIGNALS: + void started(); + void finished(); + void canceled(); + void paused(); + void resumed(); + void resultReadyAt(int resultIndex); + void resultsReadyAt(int beginIndex, int endIndex); + void progressRangeChanged(int minimum, int maximum); + void progressValueChanged(int progressValue); + void progressTextChanged(const QString &progressText); + +public Q_SLOTS: + void cancel(); + void setPaused(bool paused); + void pause(); + void resume(); + void togglePaused(); + +protected: + void connectNotify (const char * signal); + void disconnectNotify (const char * signal); + + // called from setFuture() implemented in template sub-classes + void connectOutputInterface(); + void disconnectOutputInterface(bool pendingAssignment = false); + +private: + // implemented in the template sub-classes + virtual const QFutureInterfaceBase &futureInterface() const = 0; + virtual QFutureInterfaceBase &futureInterface() = 0; +}; + +template +class QFutureWatcher : public QFutureWatcherBase +{ +public: + QFutureWatcher(QObject *_parent = 0) + : QFutureWatcherBase(_parent) + { } + ~QFutureWatcher() + { disconnectOutputInterface(); } + + void setFuture(const QFuture &future); + QFuture future() const + { return m_future; } + + T result() const { return m_future.result(); } + T resultAt(int index) const { return m_future.resultAt(index); } + +#ifdef qdoc + int progressValue() const; + int progressMinimum() const; + int progressMaximum() const; + QString progressText() const; + + bool isStarted() const; + bool isFinished() const; + bool isRunning() const; + bool isCanceled() const; + bool isPaused() const; + + void waitForFinished(); + + void setPendingResultsLimit(int limit); + +Q_SIGNALS: + void started(); + void finished(); + void canceled(); + void paused(); + void resumed(); + void resultReadyAt(int resultIndex); + void resultsReadyAt(int beginIndex, int endIndex); + void progressRangeChanged(int minimum, int maximum); + void progressValueChanged(int progressValue); + void progressTextChanged(const QString &progressText); + +public Q_SLOTS: + void cancel(); + void setPaused(bool paused); + void pause(); + void resume(); + void togglePaused(); +#endif + +private: + QFuture m_future; + const QFutureInterfaceBase &futureInterface() const { return m_future.d; } + QFutureInterfaceBase &futureInterface() { return m_future.d; } +}; + +template +Q_INLINE_TEMPLATE void QFutureWatcher::setFuture(const QFuture &_future) +{ + if (_future == m_future) + return; + + disconnectOutputInterface(true); + m_future = _future; + connectOutputInterface(); +} + +template <> +class QFutureWatcher : public QFutureWatcherBase +{ +public: + QFutureWatcher(QObject *_parent = 0) + : QFutureWatcherBase(_parent) + { } + ~QFutureWatcher() + { disconnectOutputInterface(); } + + void setFuture(const QFuture &future); + QFuture future() const + { return m_future; } + +private: + QFuture m_future; + const QFutureInterfaceBase &futureInterface() const { return m_future.d; } + QFutureInterfaceBase &futureInterface() { return m_future.d; } +}; + +Q_INLINE_TEMPLATE void QFutureWatcher::setFuture(const QFuture &_future) +{ + if (_future == m_future) + return; + + disconnectOutputInterface(true); + m_future = _future; + connectOutputInterface(); +} + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif // QFUTUREWATCHER_H diff --git a/src/concurrent/qfuturewatcher_p.h b/src/concurrent/qfuturewatcher_p.h new file mode 100644 index 0000000000..27bc49439a --- /dev/null +++ b/src/concurrent/qfuturewatcher_p.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFUTUREWATCHER_P_H +#define QFUTUREWATCHER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qfutureinterface_p.h" +#include + +#ifndef QT_NO_QFUTURE + +#include + +QT_BEGIN_NAMESPACE + +class QFutureWatcherBase; +class QFutureWatcherBasePrivate : public QObjectPrivate, + public QFutureCallOutInterface +{ + Q_DECLARE_PUBLIC(QFutureWatcherBase) + +public: + QFutureWatcherBasePrivate(); + + void postCallOutEvent(const QFutureCallOutEvent &callOutEvent); + void callOutInterfaceDisconnected(); + + void sendCallOutEvent(QFutureCallOutEvent *event); + + QList pendingCallOutEvents; + QAtomicInt pendingResultsReady; + int maximumPendingResultsReady; + + QAtomicInt resultAtConnected; + bool finished; +}; + +QT_END_NAMESPACE + +#endif // QT_NO_QFUTURE +#endif diff --git a/src/concurrent/qtconcurrentcompilertest.h b/src/concurrent/qtconcurrentcompilertest.h new file mode 100644 index 0000000000..7818423090 --- /dev/null +++ b/src/concurrent/qtconcurrentcompilertest.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTCONCURRENT_COMPILERTEST_H +#define QTCONCURRENT_COMPILERTEST_H + +#include + +#ifndef QT_NO_CONCURRENT + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +#if defined (Q_CC_MSVC) && (_MSC_VER < 1300) +# define QT_TYPENAME +#else +# define QT_TYPENAME typename +#endif + +namespace QtPrivate { + +template +class HasResultType { + typedef char Yes; + typedef void *No; + template static Yes test(int, const typename U::result_type * = 0); + template static No test(double); +public: + enum { Value = (sizeof(test(0)) == sizeof(Yes)) }; +}; + +} + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif diff --git a/src/concurrent/qtconcurrentexception.cpp b/src/concurrent/qtconcurrentexception.cpp new file mode 100644 index 0000000000..caeaa8d9be --- /dev/null +++ b/src/concurrent/qtconcurrentexception.cpp @@ -0,0 +1,211 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtconcurrentexception.h" +#include "QtCore/qshareddata.h" + +#ifndef QT_NO_QFUTURE +#ifndef QT_NO_EXCEPTIONS + +QT_BEGIN_NAMESPACE + +/*! + \class QtConcurrent::Exception + \brief The Exception class provides a base class for exceptions that can transferred across threads. + \since 4.4 + + Qt Concurrent supports throwing and catching exceptions across thread + boundaries, provided that the exception inherit from QtConcurrent::Exception + and implement two helper functions: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 0 + + QtConcurrent::Exception subclasses must be thrown by value and + caught by reference: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 1 + + If you throw an exception that is not a subclass of QtConcurrent::Exception, + the Qt Concurrent functions will throw a QtConcurrent::UnhandledException + in the receiver thread. + + When using QFuture, transferred exceptions will be thrown when calling the following functions: + \list + \o QFuture::waitForFinished() + \o QFuture::result() + \o QFuture::resultAt() + \o QFuture::results() + \endlist +*/ + +/*! + \fn QtConcurrent::Exception::raise() const + In your QtConcurrent::Exception subclass, reimplement raise() like this: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 2 +*/ + +/*! + \fn QtConcurrent::Exception::clone() const + In your QtConcurrent::Exception subclass, reimplement clone() like this: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentexception.cpp 3 +*/ + +/*! + \class QtConcurrent::UnhandledException + + \brief The UnhandledException class represents an unhandled exception in a worker thread. + \since 4.4 + + If a worker thread throws an exception that is not a subclass of QtConcurrent::Exception, + the Qt Concurrent functions will throw a QtConcurrent::UnhandledException + on the receiver thread side. + + Inheriting from this class is not supported. +*/ + +/*! + \fn QtConcurrent::UnhandledException::raise() const + \internal +*/ + +/*! + \fn QtConcurrent::UnhandledException::clone() const + \internal +*/ + +namespace QtConcurrent +{ + +void Exception::raise() const +{ + Exception e = *this; + throw e; +} + +Exception *Exception::clone() const +{ + return new Exception(*this); +} + +void UnhandledException::raise() const +{ + UnhandledException e = *this; + throw e; +} + +Exception *UnhandledException::clone() const +{ + return new UnhandledException(*this); +} + +#ifndef qdoc + +namespace internal { + +class Base : public QSharedData +{ +public: + Base(Exception *exception) + : exception(exception), hasThrown(false) { } + ~Base() { delete exception; } + + Exception *exception; + bool hasThrown; +}; + +ExceptionHolder::ExceptionHolder(Exception *exception) +: base(new Base(exception)) {} + +ExceptionHolder::ExceptionHolder(const ExceptionHolder &other) +: base(other.base) +{} + +void ExceptionHolder::operator=(const ExceptionHolder &other) +{ + base = other.base; +} + +ExceptionHolder::~ExceptionHolder() +{} + +Exception *ExceptionHolder::exception() const +{ + return base->exception; +} + +void ExceptionStore::setException(const Exception &e) +{ + if (hasException() == false) + exceptionHolder = ExceptionHolder(e.clone()); +} + +bool ExceptionStore::hasException() const +{ + return (exceptionHolder.exception() != 0); +} + +ExceptionHolder ExceptionStore::exception() +{ + return exceptionHolder; +} + +void ExceptionStore::throwPossibleException() +{ + if (hasException() ) { + exceptionHolder.base->hasThrown = true; + exceptionHolder.exception()->raise(); + } +} + +bool ExceptionStore::hasThrown() const { return exceptionHolder.base->hasThrown; } + +} // namespace internal + +#endif //qdoc + +} // namespace QtConcurrent + +QT_END_NAMESPACE + +#endif // QT_NO_EXCEPTIONS +#endif // QT_NO_CONCURRENT diff --git a/src/concurrent/qtconcurrentexception.h b/src/concurrent/qtconcurrentexception.h new file mode 100644 index 0000000000..b04e1f2a04 --- /dev/null +++ b/src/concurrent/qtconcurrentexception.h @@ -0,0 +1,128 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTCONCURRENT_EXCEPTION_H +#define QTCONCURRENT_EXCEPTION_H + +#include + +#ifndef QT_NO_QFUTURE + +#include +#include + +#ifndef QT_NO_EXCEPTIONS +# include +#endif + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +namespace QtConcurrent +{ + +#ifndef QT_NO_EXCEPTIONS + +class Q_CORE_EXPORT Exception : public std::exception +{ +public: + virtual void raise() const; + virtual Exception *clone() const; +}; + +class Q_CORE_EXPORT UnhandledException : public Exception +{ +public: + void raise() const; + Exception *clone() const; +}; + +namespace internal { + +class Base; +class ExceptionHolder +{ +public: + ExceptionHolder(Exception *exception = 0); + ExceptionHolder(const ExceptionHolder &other); + void operator=(const ExceptionHolder &other); + ~ExceptionHolder(); + Exception *exception() const; + QExplicitlySharedDataPointer base; +}; + +class Q_CORE_EXPORT ExceptionStore +{ +public: + void setException(const Exception &e); + bool hasException() const; + ExceptionHolder exception(); + void throwPossibleException(); + bool hasThrown() const; + ExceptionHolder exceptionHolder; +}; + +} // namespace internal + +#else // QT_NO_EXCEPTIONS + +namespace internal { + +class Q_CORE_EXPORT ExceptionStore +{ +public: + ExceptionStore() { } + inline void throwPossibleException() const {} +}; + +} // namespace internal + +#endif + +} // namespace QtConcurrent + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif diff --git a/src/concurrent/qtconcurrentfilter.cpp b/src/concurrent/qtconcurrentfilter.cpp new file mode 100644 index 0000000000..76ce8ca659 --- /dev/null +++ b/src/concurrent/qtconcurrentfilter.cpp @@ -0,0 +1,330 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \headerfile + \title Concurrent Filter and Filter-Reduce + \ingroup thread + + \brief The header provides concurrent Filter and + Filter-Reduce. + + These functions are a part of the \l {Concurrent Programming}{Qt Concurrent} framework. + + The QtConcurrent::filter(), QtConcurrent::filtered() and + QtConcurrent::filteredReduced() functions filter items in a sequence such + as a QList or a QVector in parallel. QtConcurrent::filter() modifies a + sequence in-place, QtConcurrent::filtered() returns a new sequence + containing the filtered content, and QtConcurrent::filteredReduced() + returns a single result. + + Each of the above functions have a blocking variant that returns the final + result instead of a QFuture. You use them in the same way as the + asynchronous variants. + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 6 + + Note that the result types above are not QFuture objects, but real result + types (in this case, QStringList and QSet). + + \section1 Concurrent Filter + + QtConcurrent::filtered() takes an input sequence and a filter function. + This filter function is then called for each item in the sequence, and a + new sequence containing the filtered values is returned. + + The filter function must be of the form: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 0 + + T must match the type stored in the sequence. The function returns true if + the item should be kept, false if it should be discarded. + + This example shows how to keep strings that are all lower-case from a + QStringList: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 1 + + The results of the filter are made available through QFuture. See the + QFuture and QFutureWatcher documentation for more information on how to + use QFuture in your applications. + + If you want to modify a sequence in-place, use QtConcurrent::filter(): + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 2 + + Since the sequence is modified in place, QtConcurrent::filter() does not + return any results via QFuture. However, you can still use QFuture and + QFutureWatcher to monitor the status of the filter. + + \section1 Concurrent Filter-Reduce + + QtConcurrent::filteredReduced() is similar to QtConcurrent::filtered(), + but instead of returing a sequence with the filtered results, the results + are combined into a single value using a reduce function. + + The reduce function must be of the form: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 3 + + T is the type of the final result, U is the type of items being filtered. + Note that the return value and return type of the reduce function are not + used. + + Call QtConcurrent::filteredReduced() like this: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 4 + + The reduce function will be called once for each result kept by the filter + function, and should merge the \e{intermediate} into the \e{result} + variable. QtConcurrent::filteredReduced() guarantees that only one thread + will call reduce at a time, so using a mutex to lock the result variable + is not necessary. The QtConcurrent::ReduceOptions enum provides a way to + control the order in which the reduction is done. + + \section1 Additional API Features + + \section2 Using Iterators instead of Sequence + + Each of the above functions has a variant that takes an iterator range + instead of a sequence. You use them in the same way as the sequence + variants: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 5 + + + \section2 Using Member Functions + + QtConcurrent::filter(), QtConcurrent::filtered(), and + QtConcurrent::filteredReduced() accept pointers to member functions. + The member function class type must match the type stored in the sequence: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 7 + + Note that when using QtConcurrent::filteredReduced(), you can mix the use of + normal and member functions freely: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 8 + + \section2 Using Function Objects + + QtConcurrent::filter(), QtConcurrent::filtered(), and + QtConcurrent::filteredReduced() accept function objects, which can be used to + add state to a function call. The result_type typedef must define the + result type of the function call operator: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 13 + + \section2 Using Bound Function Arguments + + Note that Qt does not provide support for bound functions. This is + provided by 3rd party libraries like + \l{http://www.boost.org/libs/bind/bind.html}{Boost} or + \l{http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf} + {C++ TR1 Library Extensions}. + + If you want to use a filter function takes more than one argument, you can + use boost::bind() or std::tr1::bind() to transform it onto a function that + takes one argument. + + As an example, we use QString::contains(): + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 9 + + QString::contains() takes 2 arguments (including the "this" pointer) and + can't be used with QtConcurrent::filtered() directly, because + QtConcurrent::filtered() expects a function that takes one argument. To + use QString::contains() with QtConcurrent::filtered() we have to provide a + value for the \e regexp argument: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 10 + + The return value from boost::bind() is a function object (functor) with + the following signature: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 11 + + This matches what QtConcurrent::filtered() expects, and the complete + example becomes: + + \snippet doc/src/snippets/code/src_corelib_concurrent_qtconcurrentfilter.cpp 12 +*/ + +/*! + \fn QFuture QtConcurrent::filter(Sequence &sequence, FilterFunction filterFunction) + \relates + + Calls \a filterFunction once for each item in \a sequence. If + \a filterFunction returns true, the item is kept in \a sequence; + otherwise, the item is removed from \a sequence. +*/ + +/*! + \fn QFuture QtConcurrent::filtered(const Sequence &sequence, FilterFunction filterFunction) + \relates + + Calls \a filterFunction once for each item in \a sequence and returns a + new Sequence of kept items. If \a filterFunction returns true, a copy of + the item is put in the new Sequence. Otherwise, the item will \e not + appear in the new Sequence. +*/ + +/*! + \fn QFuture QtConcurrent::filtered(ConstIterator begin, ConstIterator end, FilterFunction filterFunction) + \relates + + Calls \a filterFunction once for each item from \a begin to \a end and + returns a new Sequence of kept items. If \a filterFunction returns true, a + copy of the item is put in the new Sequence. Otherwise, the item will + \e not appear in the new Sequence. +*/ + +/*! + \fn QFuture QtConcurrent::filteredReduced(const Sequence &sequence, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions) + \relates + + Calls \a filterFunction once for each item in \a sequence. If + \a filterFunction returns true for an item, that item is then passed to + \a reduceFunction. In other words, the return value is the result of + \a reduceFunction for each item where \a filterFunction returns true. + + Note that while \a filterFunction is called concurrently, only one thread + at a time will call \a reduceFunction. The order in which \a reduceFunction + is called is undefined if \a reduceOptions is + QtConcurrent::UnorderedReduce. If \a reduceOptions is + QtConcurrent::OrderedReduce, \a reduceFunction is called in the order of + the original sequence. +*/ + +/*! + \fn QFuture QtConcurrent::filteredReduced(ConstIterator begin, ConstIterator end, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions) + \relates + + Calls \a filterFunction once for each item from \a begin to \a end. If + \a filterFunction returns true for an item, that item is then passed to + \a reduceFunction. In other words, the return value is the result of + \a reduceFunction for each item where \a filterFunction returns true. + + Note that while \a filterFunction is called concurrently, only one thread + at a time will call \a reduceFunction. The order in which + \a reduceFunction is called is undefined if \a reduceOptions is + QtConcurrent::UnorderedReduce. If \a reduceOptions is + QtConcurrent::OrderedReduce, the \a reduceFunction is called in the order + of the original sequence. +*/ + +/*! + \fn void QtConcurrent::blockingFilter(Sequence &sequence, FilterFunction filterFunction) + + Calls \a filterFunction once for each item in \a sequence. If + \a filterFunction returns true, the item is kept in \a sequence; + otherwise, the item is removed from \a sequence. + + \note This function will block until all items in the sequence have been processed. +*/ + +/*! + \fn Sequence QtConcurrent::blockingFiltered(const Sequence &sequence, FilterFunction filterFunction) + + Calls \a filterFunction once for each item in \a sequence and returns a + new Sequence of kept items. If \a filterFunction returns true, a copy of + the item is put in the new Sequence. Otherwise, the item will \e not + appear in the new Sequence. + + \note This function will block until all items in the sequence have been processed. + + \sa filtered() +*/ + +/*! + \fn Sequence QtConcurrent::blockingFiltered(ConstIterator begin, ConstIterator end, FilterFunction filterFunction) + + Calls \a filterFunction once for each item from \a begin to \a end and + returns a new Sequence of kept items. If \a filterFunction returns true, a + copy of the item is put in the new Sequence. Otherwise, the item will + \e not appear in the new Sequence. + + \note This function will block until the iterator reaches the end of the + sequence being processed. + + \sa filtered() +*/ + +/*! + \fn T QtConcurrent::blockingFilteredReduced(const Sequence &sequence, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions) + + Calls \a filterFunction once for each item in \a sequence. If + \a filterFunction returns true for an item, that item is then passed to + \a reduceFunction. In other words, the return value is the result of + \a reduceFunction for each item where \a filterFunction returns true. + + Note that while \a filterFunction is called concurrently, only one thread + at a time will call \a reduceFunction. The order in which \a reduceFunction + is called is undefined if \a reduceOptions is + QtConcurrent::UnorderedReduce. If \a reduceOptions is + QtConcurrent::OrderedReduce, \a reduceFunction is called in the order of + the original sequence. + + \note This function will block until all items in the sequence have been processed. + + \sa filteredReduced() +*/ + +/*! + \fn T QtConcurrent::blockingFilteredReduced(ConstIterator begin, ConstIterator end, FilterFunction filterFunction, ReduceFunction reduceFunction, QtConcurrent::ReduceOptions reduceOptions) + + Calls \a filterFunction once for each item from \a begin to \a end. If + \a filterFunction returns true for an item, that item is then passed to + \a reduceFunction. In other words, the return value is the result of + \a reduceFunction for each item where \a filterFunction returns true. + + Note that while \a filterFunction is called concurrently, only one thread + at a time will call \a reduceFunction. The order in which + \a reduceFunction is called is undefined if \a reduceOptions is + QtConcurrent::UnorderedReduce. If \a reduceOptions is + QtConcurrent::OrderedReduce, the \a reduceFunction is called in the order + of the original sequence. + + \note This function will block until the iterator reaches the end of the + sequence being processed. + + \sa filteredReduced() +*/ diff --git a/src/concurrent/qtconcurrentfilter.h b/src/concurrent/qtconcurrentfilter.h new file mode 100644 index 0000000000..1de8d230b1 --- /dev/null +++ b/src/concurrent/qtconcurrentfilter.h @@ -0,0 +1,269 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTCONCURRENT_FILTER_H +#define QTCONCURRENT_FILTER_H + +#include + +#ifndef QT_NO_CONCURRENT + +#include +#include + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +#ifdef qdoc + +namespace QtConcurrent { + + QFuture filter(Sequence &sequence, FilterFunction filterFunction); + + template + QFuture filtered(const Sequence &sequence, FilterFunction filterFunction); + template + QFuture filtered(ConstIterator begin, ConstIterator end, FilterFunction filterFunction); + + template + QFuture filteredReduced(const Sequence &sequence, + FilterFunction filterFunction, + ReduceFunction reduceFunction, + QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce); + template + QFuture filteredReduced(ConstIterator begin, + ConstIterator end, + FilterFunction filterFunction, + ReduceFunction reduceFunction, + QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce); + + void blockingFilter(Sequence &sequence, FilterFunction filterFunction); + + template + Sequence blockingFiltered(const Sequence &sequence, FilterFunction filterFunction); + template + Sequence blockingFiltered(ConstIterator begin, ConstIterator end, FilterFunction filterFunction); + + template + T blockingFilteredReduced(const Sequence &sequence, + FilterFunction filterFunction, + ReduceFunction reduceFunction, + QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce); + template + T blockingFilteredReduced(ConstIterator begin, + ConstIterator end, + FilterFunction filterFunction, + ReduceFunction reduceFunction, + QtConcurrent::ReduceOptions reduceOptions = UnorderedReduce | SequentialReduce); + +} // namespace QtConcurrent + +#else + +namespace QtConcurrent { + +template +ThreadEngineStarter filterInternal(Sequence &sequence, KeepFunctor keep, ReduceFunctor reduce) +{ + typedef typename Sequence::const_iterator Iterator; + typedef FilterKernel KernelType; + return startThreadEngine(new KernelType(sequence, keep, reduce)); +} + +// filter() on sequences +template +QFuture filter(Sequence &sequence, KeepFunctor keep) +{ + return filterInternal(sequence, QtPrivate::createFunctionWrapper(keep), QtPrivate::PushBackWrapper()); +} + +// filteredReduced() on sequences +template +QFuture filteredReduced(const Sequence &sequence, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced(sequence, QtPrivate::createFunctionWrapper(keep), QtPrivate::createFunctionWrapper(reduce), options); +} + +template +QFuture::ResultType> filteredReduced(const Sequence &sequence, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced::ResultType> + (sequence, + QtPrivate::createFunctionWrapper(keep), + QtPrivate::createFunctionWrapper(reduce), + options); +} + +// filteredReduced() on iterators +template +QFuture filteredReduced(Iterator begin, + Iterator end, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced(begin, end, QtPrivate::createFunctionWrapper(keep), QtPrivate::createFunctionWrapper(reduce), options); +} + +template +QFuture::ResultType> filteredReduced(Iterator begin, + Iterator end, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced::ResultType> + (begin, end, + QtPrivate::createFunctionWrapper(keep), + QtPrivate::createFunctionWrapper(reduce), + options); +} + +// filtered() on sequences +template +QFuture filtered(const Sequence &sequence, KeepFunctor keep) +{ + return startFiltered(sequence, QtPrivate::createFunctionWrapper(keep)); +} + +// filtered() on iterators +template +QFuture::value_type> filtered(Iterator begin, Iterator end, KeepFunctor keep) +{ + return startFiltered(begin, end, QtPrivate::createFunctionWrapper(keep)); +} + +// blocking filter() on sequences +template +void blockingFilter(Sequence &sequence, KeepFunctor keep) +{ + filterInternal(sequence, QtPrivate::createFunctionWrapper(keep), QtPrivate::PushBackWrapper()).startBlocking(); +} + +// blocking filteredReduced() on sequences +template +ResultType blockingFilteredReduced(const Sequence &sequence, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced(sequence, QtPrivate::createFunctionWrapper(keep), QtPrivate::createFunctionWrapper(reduce), options) + .startBlocking(); +} + +template +typename QtPrivate::ReduceResultType::ResultType blockingFilteredReduced(const Sequence &sequence, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return blockingFilteredReduced::ResultType> + (sequence, + QtPrivate::createFunctionWrapper(keep), + QtPrivate::createFunctionWrapper(reduce), + options); +} + +// blocking filteredReduced() on iterators +template +ResultType blockingFilteredReduced(Iterator begin, + Iterator end, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced + (begin, end, + QtPrivate::createFunctionWrapper(keep), + QtPrivate::createFunctionWrapper(reduce), + options) + .startBlocking(); +} + +template +typename QtPrivate::ReduceResultType::ResultType blockingFilteredReduced(Iterator begin, + Iterator end, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOptions options = ReduceOptions(UnorderedReduce | SequentialReduce)) +{ + return startFilteredReduced::ResultType> + (begin, end, + QtPrivate::createFunctionWrapper(keep), + QtPrivate::createFunctionWrapper(reduce), + options) + .startBlocking(); +} + +// blocking filtered() on sequences +template +Sequence blockingFiltered(const Sequence &sequence, KeepFunctor keep) +{ + return startFilteredReduced(sequence, QtPrivate::createFunctionWrapper(keep), QtPrivate::PushBackWrapper(), OrderedReduce).startBlocking(); +} + +// blocking filtered() on iterators +template +OutputSequence blockingFiltered(Iterator begin, Iterator end, KeepFunctor keep) +{ + return startFilteredReduced(begin, end, + QtPrivate::createFunctionWrapper(keep), + QtPrivate::PushBackWrapper(), + OrderedReduce).startBlocking(); +} + +} // namespace QtConcurrent + +#endif // qdoc + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif diff --git a/src/concurrent/qtconcurrentfilterkernel.h b/src/concurrent/qtconcurrentfilterkernel.h new file mode 100644 index 0000000000..71112cb5a3 --- /dev/null +++ b/src/concurrent/qtconcurrentfilterkernel.h @@ -0,0 +1,350 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTCONCURRENT_FILTERKERNEL_H +#define QTCONCURRENT_FILTERKERNEL_H + +#include + +#ifndef QT_NO_CONCURRENT + +#include +#include +#include + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +#ifndef qdoc + +namespace QtConcurrent { + +template +struct qValueType +{ + typedef typename T::value_type value_type; +}; + +template +struct qValueType +{ + typedef T value_type; +}; + +template +struct qValueType +{ + typedef T value_type; +}; + +// Implementation of filter +template +class FilterKernel : public IterateKernel +{ + typedef ReduceKernel Reducer; + typedef IterateKernel IterateKernelType; + typedef typename ReduceFunctor::result_type T; + + Sequence reducedResult; + Sequence &sequence; + KeepFunctor keep; + ReduceFunctor reduce; + Reducer reducer; + +public: + FilterKernel(Sequence &_sequence, KeepFunctor _keep, ReduceFunctor _reduce) + : IterateKernelType(const_cast(_sequence).begin(), const_cast(_sequence).end()), reducedResult(), + sequence(_sequence), + keep(_keep), + reduce(_reduce), + reducer(OrderedReduce) + { } + + bool runIteration(typename Sequence::const_iterator it, int index, T *) + { + IntermediateResults results; + results.begin = index; + results.end = index + 1; + + if (keep(*it)) + results.vector.append(*it); + + reducer.runReduce(reduce, reducedResult, results); + return false; + } + + bool runIterations(typename Sequence::const_iterator sequenceBeginIterator, int begin, int end, T *) + { + IntermediateResults results; + results.begin = begin; + results.end = end; + results.vector.reserve(end - begin); + + + typename Sequence::const_iterator it = sequenceBeginIterator; + advance(it, begin); + for (int i = begin; i < end; ++i) { + if (keep(*it)) + results.vector.append(*it); + advance(it, 1); + } + + reducer.runReduce(reduce, reducedResult, results); + return false; + } + + void finish() + { + reducer.finish(reduce, reducedResult); + sequence = reducedResult; + } + + inline bool shouldThrottleThread() + { + return IterateKernelType::shouldThrottleThread() || reducer.shouldThrottle(); + } + + inline bool shouldStartThread() + { + return IterateKernelType::shouldStartThread() && reducer.shouldStartThread(); + } + + typedef void ReturnType; + typedef void ResultType; +}; + +// Implementation of filter-reduce +template ::value_type> > +class FilteredReducedKernel : public IterateKernel +{ + ReducedResultType reducedResult; + KeepFunctor keep; + ReduceFunctor reduce; + Reducer reducer; + typedef IterateKernel IterateKernelType; + +public: + FilteredReducedKernel(Iterator begin, + Iterator end, + KeepFunctor _keep, + ReduceFunctor _reduce, + ReduceOptions reduceOption) + : IterateKernelType(begin, end), reducedResult(), keep(_keep), reduce(_reduce), reducer(reduceOption) + { } + +#if 0 + FilteredReducedKernel(ReducedResultType initialValue, + KeepFunctor keep, + ReduceFunctor reduce, + ReduceOption reduceOption) + : reducedResult(initialValue), keep(keep), reduce(reduce), reducer(reduceOption) + { } +#endif + + bool runIteration(Iterator it, int index, ReducedResultType *) + { + IntermediateResults::value_type> results; + results.begin = index; + results.end = index + 1; + + if (keep(*it)) + results.vector.append(*it); + + reducer.runReduce(reduce, reducedResult, results); + return false; + } + + bool runIterations(Iterator sequenceBeginIterator, int begin, int end, ReducedResultType *) + { + IntermediateResults::value_type> results; + results.begin = begin; + results.end = end; + results.vector.reserve(end - begin); + + Iterator it = sequenceBeginIterator; + advance(it, begin); + for (int i = begin; i < end; ++i) { + if (keep(*it)) + results.vector.append(*it); + advance(it, 1); + } + + reducer.runReduce(reduce, reducedResult, results); + return false; + } + + void finish() + { + reducer.finish(reduce, reducedResult); + } + + inline bool shouldThrottleThread() + { + return IterateKernelType::shouldThrottleThread() || reducer.shouldThrottle(); + } + + inline bool shouldStartThread() + { + return IterateKernelType::shouldStartThread() && reducer.shouldStartThread(); + } + + typedef ReducedResultType ReturnType; + typedef ReducedResultType ResultType; + ReducedResultType *result() + { + return &reducedResult; + } +}; + +// Implementation of filter that reports individual results via QFutureInterface +template +class FilteredEachKernel : public IterateKernel::value_type> +{ + typedef typename qValueType::value_type T; + typedef IterateKernel IterateKernelType; + + KeepFunctor keep; + +public: + typedef T ReturnType; + typedef T ResultType; + + FilteredEachKernel(Iterator begin, Iterator end, KeepFunctor _keep) + : IterateKernelType(begin, end), keep(_keep) + { } + + void start() + { + if (this->futureInterface) + this->futureInterface->setFilterMode(true); + IterateKernelType::start(); + } + + bool runIteration(Iterator it, int index, T *) + { + if (keep(*it)) + this->reportResult(&(*it), index); + else + this->reportResult(0, index); + return false; + } + + bool runIterations(Iterator sequenceBeginIterator, int begin, int end, T *) + { + const int count = end - begin; + IntermediateResults::value_type> results; + results.begin = begin; + results.end = end; + results.vector.reserve(count); + + Iterator it = sequenceBeginIterator; + advance(it, begin); + for (int i = begin; i < end; ++i) { + if (keep(*it)) + results.vector.append(*it); + advance(it, 1); + } + + this->reportResults(results.vector, begin, count); + return false; + } +}; + +template +inline +ThreadEngineStarter::value_type> +startFiltered(Iterator begin, Iterator end, KeepFunctor functor) +{ + return startThreadEngine(new FilteredEachKernel(begin, end, functor)); +} + +template +inline ThreadEngineStarter +startFiltered(const Sequence &sequence, KeepFunctor functor) +{ + typedef SequenceHolder1, + KeepFunctor> + SequenceHolderType; + return startThreadEngine(new SequenceHolderType(sequence, functor)); +} + +template +inline ThreadEngineStarter startFilteredReduced(const Sequence & sequence, + MapFunctor mapFunctor, ReduceFunctor reduceFunctor, + ReduceOptions options) +{ + typedef typename Sequence::const_iterator Iterator; + typedef ReduceKernel::value_type > Reducer; + typedef FilteredReducedKernel FilteredReduceType; + typedef SequenceHolder2 SequenceHolderType; + return startThreadEngine(new SequenceHolderType(sequence, mapFunctor, reduceFunctor, options)); +} + + +template +inline ThreadEngineStarter startFilteredReduced(Iterator begin, Iterator end, + MapFunctor mapFunctor, ReduceFunctor reduceFunctor, + ReduceOptions options) +{ + typedef ReduceKernel::value_type> Reducer; + typedef FilteredReducedKernel FilteredReduceType; + return startThreadEngine(new FilteredReduceType(begin, end, mapFunctor, reduceFunctor, options)); +} + + +} // namespace QtConcurrent + +#endif // qdoc + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // QT_NO_CONCURRENT + +#endif diff --git a/src/concurrent/qtconcurrentfunctionwrappers.h b/src/concurrent/qtconcurrentfunctionwrappers.h new file mode 100644 index 0000000000..9b86b73f6d --- /dev/null +++ b/src/concurrent/qtconcurrentfunctionwrappers.h @@ -0,0 +1,303 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTCONCURRENT_FUNCTIONWRAPPERS_H +#define QTCONCURRENT_FUNCTIONWRAPPERS_H + +#include + +#ifndef QT_NO_CONCURRENT + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + + +#ifndef qdoc + +namespace QtConcurrent { + +template +class FunctionWrapper0 +{ +public: + typedef T (*FunctionPointerType)(); + typedef T result_type; + inline FunctionWrapper0(FunctionPointerType _functionPointer) + :functionPointer(_functionPointer) { } + + inline T operator()() + { + return functionPointer(); + } +private: + FunctionPointerType functionPointer; +}; + +template +class FunctionWrapper1 +{ +public: + typedef T (*FunctionPointerType)(U u); + typedef T result_type; + inline FunctionWrapper1(FunctionPointerType _functionPointer) + :functionPointer(_functionPointer) { } + + inline T operator()(U u) + { + return functionPointer(u); + } + +private: + FunctionPointerType functionPointer; +}; + +template +class FunctionWrapper2 +{ +public: + typedef T (*FunctionPointerType)(U u, V v); + typedef T result_type; + inline FunctionWrapper2(FunctionPointerType _functionPointer) + :functionPointer(_functionPointer) { } + + inline T operator()(U u, V v) + { + return functionPointer(u, v); + } +private: + FunctionPointerType functionPointer; +}; + +template +class MemberFunctionWrapper +{ +public: + typedef T (C::*FunctionPointerType)(); + typedef T result_type; + inline MemberFunctionWrapper(FunctionPointerType _functionPointer) + :functionPointer(_functionPointer) { } + + inline T operator()(C &c) + { + return (c.*functionPointer)(); + } +private: + FunctionPointerType functionPointer; +}; + +template +class MemberFunctionWrapper1 +{ +public: + typedef T (C::*FunctionPointerType)(U); + typedef T result_type; + + inline MemberFunctionWrapper1(FunctionPointerType _functionPointer) + : functionPointer(_functionPointer) + { } + + inline T operator()(C &c, U u) + { + return (c.*functionPointer)(u); + } + +private: + FunctionPointerType functionPointer; +}; + +template +class ConstMemberFunctionWrapper +{ +public: + typedef T (C::*FunctionPointerType)() const; + typedef T result_type; + inline ConstMemberFunctionWrapper(FunctionPointerType _functionPointer) + :functionPointer(_functionPointer) { } + + inline T operator()(const C &c) const + { + return (c.*functionPointer)(); + } +private: + FunctionPointerType functionPointer; +}; + +} // namespace QtConcurrent. + +namespace QtPrivate { + +template +const T& createFunctionWrapper(const T& t) +{ + return t; +} + +template +QtConcurrent::FunctionWrapper1 createFunctionWrapper(T (*func)(U)) +{ + return QtConcurrent::FunctionWrapper1(func); +} + +template +QtConcurrent::MemberFunctionWrapper createFunctionWrapper(T (C::*func)()) +{ + return QtConcurrent::MemberFunctionWrapper(func); +} + +template +QtConcurrent::MemberFunctionWrapper1 createFunctionWrapper(T (C::*func)(U)) +{ + return QtConcurrent::MemberFunctionWrapper1(func); +} + +template +QtConcurrent::ConstMemberFunctionWrapper createFunctionWrapper(T (C::*func)() const) +{ + return QtConcurrent::ConstMemberFunctionWrapper(func); +} + +struct PushBackWrapper +{ + typedef void result_type; + + template + inline void operator()(C &c, const U &u) const + { + return c.push_back(u); + } + +#ifdef Q_COMPILER_RVALUE_REFS + template + inline void operator()(C &c, U &&u) const + { + return c.push_back(u); + } +#endif +}; + +template ::Value> +struct LazyResultType { typedef typename Functor::result_type Type; }; +template +struct LazyResultType { typedef void Type; }; + +template +struct ReduceResultType; + +template +struct ReduceResultType +{ + typedef U ResultType; +}; + +template +struct ReduceResultType +{ + typedef C ResultType; +}; + +template +struct MapResultType +{ + typedef typename LazyResultType::Type ResultType; +}; + +template +struct MapResultType +{ + typedef U ResultType; +}; + +template +struct MapResultType +{ + typedef T ResultType; +}; + +#ifndef QT_NO_TEMPLATE_TEMPLATE_PARAMETERS + +template