Cómo: Usar la cancelación para interrumpir un bucle Parallel

En este ejemplo se muestra cómo se usa la cancelación para implementar un algoritmo de búsqueda paralelo.

Ejemplo

En el siguiente ejemplo se usa la cancelación para buscar un elemento en una matriz. La función parallel_find_any usa el algoritmo Concurrency::parallel_for y un objeto Concurrency::structured_task_group para buscar la posición que contiene el valor indicado. Cuando una función de trabajo encuentra el valor, llama al método Concurrency::structured_task_group::cancel para cancelar el trabajo posterior. El runtime cancela cualquier tarea activa y no inicia ninguna nueva.

// 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;
   }  
}

A continuación, se muestra la salida de este ejemplo.

3123 is at position 4739.

El algoritmo Concurrency::parallel_for actúa de manera simultánea. Por consiguiente, no realiza las operaciones en un orden predeterminado. Si la matriz contiene varias instancias del valor, el resultado puede ser cualquiera de sus posiciones.

Compilar el código

Copie el código de ejemplo y péguelo en un proyecto de Visual Studio o péguelo en un archivo denominado parallel-array-search.cpp y, a continuación, ejecute el siguiente comando en una ventana del símbolo del sistema de Visual Studio 2010.

cl.exe /EHsc parallel-array-search.cpp

Vea también

Referencia

parallel_for (Función)

structured_task_group (Clase)

Conceptos

Cancelación en la biblioteca PPL

Algoritmos paralelos