Procedura: utilizzare l'annullamento per interrompere un ciclo Parallel

In questo esempio viene illustrato come utilizzare l'annullamento per implementare un algoritmo di ricerca parallelo.

Esempio

Nell'esempio seguente viene utilizzato l'annullamento per cercare un elemento in una matrice. La funzione parallel_find_any utilizza l'algoritmo Concurrency::parallel_for e un oggetto Concurrency::structured_task_group per cercare la posizione che contiene il valore specificato. Quando una funzione lavoro trova il valore, chiama il metodo Concurrency::structured_task_group::cancel per annullare il lavoro futuro. Il runtime annulla tutte le attività attive e non ne avvia di nuove.

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

Questo esempio produce l'output seguente:

3123 is at position 4739.

L'algoritmo Concurrency::parallel_for agisce contemporaneamente. Pertanto, non esegue le operazioni in un ordine predeterminato. Se la matrice contiene più istanze del valore, il risultato può essere una delle relative posizioni.

Compilazione del codice

Copiare il codice di esempio e incollarlo in un progetto di Visual Studio o incollarlo in un file denominato parallel-array-search.cpp, quindi eseguire il comando seguente in una finestra del prompt dei comandi di Visual Studio 2010.

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

Vedere anche

Riferimenti

Funzione parallel_for

Classe structured_task_group

Concetti

Annullamento nella libreria PPL

Algoritmi paralleli