Share via


방법: 취소를 사용하여 병렬 루프 중단

이 예제에서는 취소를 사용하여 기본적인 병렬 검색 알고리즘을 구현하는 방법을 보여 줍니다.

예시

다음 예제에서는 취소를 사용하여 배열의 요소를 검색합니다. 이 함수는 parallel_find_any concurrency::p arallel_for 알고리즘 및 동시성::run_with_cancellation_token 함수를 사용하여 지정된 값이 포함된 위치를 검색합니다. 병렬 루프가 값을 찾으면 동시성::cancellation_token_source::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;

   // 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.
*/

concurrency::p arallel_for 알고리즘은 동시에 작동합니다. 따라서 미리 결정된 순서로 작업을 수행하지 않습니다. 배열에 값의 여러 인스턴스가 포함된 경우 결과는 해당 위치 중 하나일 수 있습니다.

코드 컴파일

예제 코드를 복사하여 Visual Studio 프로젝트에 붙여넣거나 이름이 지정된 parallel-array-search.cpp 파일에 붙여넣은 다음 Visual Studio 명령 프롬프트 창에서 다음 명령을 실행합니다.

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

참고 항목

PPL에서의 취소
병렬 알고리즘
parallel_for 함수
cancellation_token_source 클래스