Практическое руководство. Использование отмены для выхода из параллельного цикла
В этом примере показано, как использовать отмену для реализации алгоритма параллельного поиска.
Пример
В следующем примере отмена используется для поиска элемента в массиве. Функция parallel_find_any использует алгоритм Concurrency::parallel_for и объект Concurrency::structured_task_group для поиска позиции, содержащей данное значение. Когда рабочая функция находит это значение, она вызывает метод Concurrency::structured_task_group::cancel для отмены дальнейшей работы. Среда выполнения отменяет все активные задачи и не запускает новые.
// parallel-array-search.cpp
// compile with: /EHsc
#include <ppl.h>
#include <iostream>
#include <random>
using namespace Concurrency;
using namespace std;
// Returns the position in the provided array that contains the given value,
// or -1 if the value is not in the array.
template<typename T>
int parallel_find_any(const T a[], size_t count, const T& what)
{
// The position of the element in the array.
// The default value, -1, indicates that the element is not in the array.
int position = -1;
// Use parallel_for to search for the element.
// The task group enables a work function to cancel the overall
// operation when it finds the result.
structured_task_group tasks;
tasks.run_and_wait([&]
{
parallel_for(std::size_t(0), count, [&](int n) {
if (a[n] == what)
{
// Set the return value and cancel the remaining tasks.
position = n;
tasks.cancel();
}
});
});
return position;
}
int wmain()
{
const size_t count = 10000;
int values[count];
// Fill the array with random values.
mt19937 gen(34);
for (size_t i = 0; i < count; ++i)
{
values[i] = gen()%10000;
}
// Search for any position in the array that contains value 3123.
const int what = 3123;
int position = parallel_find_any(values, count, what);
if (position >= 0)
{
wcout << what << L" is at position " << position << L'.' << endl;
}
else
{
wcout << what << L" is not in the array." << endl;
}
}
Ниже приведен пример выходных данных для данного примера.
3123 is at position 4739.
Алгоритм Concurrency::parallel_for работает параллельно. Поэтому он не выполняет операции в заранее заданном порядке. Если массив содержит несколько вхождений требуемого значения, результатом может быть любая из таких позиций.
Компиляция кода
Скопируйте код примера и вставьте его в проект Visual Studio или в файл с именем parallel-array-search.cpp, затем выполните в окне командной строки Visual Studio 2010 следующую команду.
cl.exe /EHsc parallel-array-search.cpp