IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)

Concurrent Filter and Filter-Reduce

Selecting values from a sequence and combining them, all in parallel.

Article lu   fois.

L'auteur

Liens sociaux

Viadeo Twitter Facebook Share on Google+   

Concurrent Filter and Filter-Reduce

The QtConcurrent::filter(), QtConcurrent::filtered() and QtConcurrent::filteredReduced() functions filter items in a sequence such as a QList 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.

These functions are part of the Qt Concurrent framework.

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.

 
Sélectionnez
QStringList strings = ...;

// each call blocks until the entire operation is finished
QStringList lowerCaseStrings = QtConcurrent::blockingFiltered(strings, allLowerCase);

QtConcurrent::blockingFilter(strings, allLowerCase);

QSet<QString> dictionary = QtConcurrent::blockingFilteredReduced(strings, allLowerCase, addToDictionary);

Note that the result types above are not QFuture objects, but real result types (in this case, QStringList and QSet<QString>).

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:

 
Sélectionnez
bool function(const T &amp;t);

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:

 
Sélectionnez
bool allLowerCase(const QString &amp;string)
{
    return string.lowered() == string;
}

QStringList strings = ...;
QFuture&lt;QString&gt; lowerCaseStrings = QtConcurrent::filtered(strings, allLowerCase);

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

 
Sélectionnez
QStringList strings = ...;
QFuture&lt;void&gt; future = QtConcurrent::filter(strings, allLowerCase);

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.

Concurrent Filter-Reduce

QtConcurrent::filteredReduced() is similar to QtConcurrent::filtered(), but instead of returning 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:

 
Sélectionnez
V function(T &amp;result, const U &amp;intermediate)

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:

 
Sélectionnez
void addToDictionary(QSet&lt;QString&gt; &amp;dictionary, const QString &amp;string)
{
    dictionary.insert(string);
}

QStringList strings = ...;
QFuture&lt;QSet&lt;QString&gt;&gt; dictionary = QtConcurrent::filteredReduced(strings, allLowerCase, addToDictionary);

The reduce function will be called once for each result kept by the filter function, and should merge the intermediate into the 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.

Additional API Features

 

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:

 
Sélectionnez
QStringList strings = ...;
QFuture&lt;QString&gt; lowerCaseStrings = QtConcurrent::filtered(strings.constBegin(), strings.constEnd(), allLowerCase);

// filter in-place only works on non-const iterators
QFuture&lt;void&gt; future = QtConcurrent::filter(strings.begin(), strings.end(), allLowerCase);

QFuture&lt;QSet&lt;QString&gt;&gt; dictionary = QtConcurrent::filteredReduced(strings.constBegin(), strings.constEnd(), allLowerCase, addToDictionary);

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:

 
Sélectionnez
// keep only images with an alpha channel
QList&lt;QImage&gt; images = ...;
QFuture&lt;void&gt; alphaImages = QtConcurrent::filter(images, &amp;QImage::hasAlphaChannel);

// retrieve gray scale images
QList&lt;QImage&gt; images = ...;
QFuture&lt;QImage&gt; grayscaleImages = QtConcurrent::filtered(images, &amp;QImage::isGrayscale);

// create a set of all printable characters
QList&lt;QChar&gt; characters = ...;
QFuture&lt;QSet&lt;QChar&gt;&gt; set = QtConcurrent::filteredReduced(characters, qOverload&lt;&gt;(&amp;QChar::isPrint),
                                                         qOverload&lt;const QChar&amp;&gt;(&amp;QSet&lt;QChar&gt;::insert));

Note the use of qOverload. It is needed to resolve the ambiguity for the methods, that have multiple overloads.

Also note that when using QtConcurrent::filteredReduced(), you can mix the use of normal and member functions freely:

 
Sélectionnez
// can mix normal functions and member functions with QtConcurrent::filteredReduced()

// create a dictionary of all lower cased strings
extern bool allLowerCase(const QString &amp;string);
QStringList strings = ...;
QFuture&lt;QSet&lt;QString&gt;&gt; lowerCase = QtConcurrent::filteredReduced(strings, allLowerCase,
                                                                 qOverload&lt;const QString&amp;&gt;(&amp;QSet&lt;QString&gt;::insert));

// create a collage of all gray scale images
extern void addToCollage(QImage &amp;collage, const QImage &amp;grayscaleImage);
QList&lt;QImage&gt; images = ...;
QFuture&lt;QImage&gt; collage = QtConcurrent::filteredReduced(images, &amp;QImage::isGrayscale, addToCollage);

Using Function Objects

QtConcurrent::filter(), QtConcurrent::filtered(), and QtConcurrent::filteredReduced() accept function objects for the filter function. These function objects can be used to add state to a function call:

 
Sélectionnez
struct StartsWith
{
    StartsWith(const QString &amp;string)
    : m_string(string) { }

    bool operator()(const QString &amp;testString)
    {
        return testString.startsWith(m_string);
    }

    QString m_string;
};

QList&lt;QString&gt; strings = ...;
QFuture&lt;QString&gt; fooString = QtConcurrent::filtered(strings, StartsWith(QLatin1String("Foo")));

Function objects are also supported for the reduce function:

 
Sélectionnez
struct StringTransform
{
    void operator()(QString &amp;result, const QString &amp;value);
};

QFuture&lt;QString&gt; fooString =
        QtConcurrent::filteredReduced(strings, StartsWith(QLatin1String("Foo")), StringTransform());

Using Lambda Expressions

QtConcurrent::filter(), QtConcurrent::filtered(), and QtConcurrent::filteredReduced() accept lambda expressions for the filter and reduce function:

 
Sélectionnez
// keep only even integers
QList&lt;int&gt; list { 1, 2, 3, 4 };
QtConcurrent::blockingFilter(list, [](int n) { return (n &amp; 1) == 0; });

// retrieve only even integers
QList&lt;int&gt; list2 { 1, 2, 3, 4 };
QFuture&lt;int&gt; future = QtConcurrent::filtered(list2, [](int x) {
    return (x &amp; 1) == 0;
});
QList&lt;int&gt; results = future.results();

// add up all even integers
QList&lt;int&gt; list3 { 1, 2, 3, 4 };
QFuture&lt;int&gt; sum = QtConcurrent::filteredReduced(list3,
    [](int x) {
        return (x &amp; 1) == 0;
    },
    [](int &amp;sum, int x) {
        sum += x;
    }
);

When using QtConcurrent::filteredReduced() or QtConcurrent::blockingFilteredReduced(), you can mix the use of normal functions, member functions and lambda expressions freely.

 
Sélectionnez
void intSumReduce(int &amp;sum, int x)
{
    sum += x;
}

QList&lt;int&gt; list { 1, 2, 3, 4 };
QFuture&lt;int&gt; sum = QtConcurrent::filteredReduced(list,
    [] (int x) {
        return (x &amp; 1) == 0;
    },
    intSumReduce
);

You can also pass a lambda as a reduce object:

 
Sélectionnez
bool keepEvenIntegers(int x)
{
    return (x &amp; 1) == 0;
}

QList&lt;int&gt; list { 1, 2, 3, 4 };
QFuture&lt;int&gt; sum = QtConcurrent::filteredReduced(list,
    keepEvenIntegers,
    [](int &amp;sum, int x) {
        sum += x;
    }
);

Wrapping Functions that Take Multiple Arguments

If you want to use a filter function takes more than one argument, you can use a lambda function or std::bind() to transform it onto a function that takes one argument.

As an example, we use QString::contains():

 
Sélectionnez
bool QString::contains(const QRegularExpression &amp;regexp) const;

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 regexp argument:

 
Sélectionnez
QStringList strings = ...;
QFuture&lt;QString&gt; future = QtConcurrent::filtered(list, [](const QString &amp;str) {
    return str.contains(QRegularExpression("^\\S+$")); // matches strings without whitespace
});

Vous avez aimé ce tutoriel ? Alors partagez-le en cliquant sur les boutons suivants : Viadeo Twitter Facebook Share on Google+