How to: Use Cancellation to Break from a Parallel Loop

This example shows how to use cancellation to implement a basic parallel search algorithm.

The following example uses cancellation to search for an element in an array. The parallel_find_any function uses the concurrency::parallel_for algorithm and the concurrency::run_with_cancellation_token function to search for the position that contains the given value. When the parallel loop finds the value, it calls the concurrency::cancellation_token_source::cancel method to cancel future work.

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

   // Call parallel_for in the context of a cancellation token to search for the element.
   cancellation_token_source cts;
   run_with_cancellation_token([count, what, &a, &position, &cts]()
   {
      parallel_for(std::size_t(0), count, [what, &a, &position, &cts](int n) {
         if (a[n] == what)
         {
            // Set the return value and cancel the remaining tasks.
            position = n;
            cts.cancel();
         }
      });
   }, cts.get_token());

   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;
   }
}
/* Sample output:
    3123 is at position 7835.
*/

The concurrency::parallel_for algorithm acts concurrently. Therefore, it does not perform the operations in a pre-determined order. If the array contains multiple instances of the value, the result can be any one of its positions.

Copy the example code and paste it in a Visual Studio project, or paste it in a file that is named parallel-array-search.cpp and then run the following command in a Visual Studio Command Prompt window.

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

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft