방법: combinable을 사용하여 집합 결합

이 항목에서는 동시성::결합 가능한 클래스를 사용하여 소수 집합을 계산하는 방법을 보여 줍니다.

예시

다음 예제에서는 소수 집합을 두 번 계산합니다. 각 계산은 결과를 std::bitset 개체에 저장합니다. 이 예제에서는 먼저 집합을 직렬로 계산한 다음 집합을 병렬로 계산합니다. 또한 이 예제에서는 두 계산을 모두 수행하는 데 필요한 시간을 콘솔에 출력합니다.

이 예제에서는 concurrency::p arallel_for 알고리즘 및 개체를 combinable 사용하여 스레드-로컬 집합을 생성합니다. 그런 다음 동시성::combinable::combine_each 메서드를 사용하여 스레드 로컬 집합을 최종 집합으로 결합합니다.

// parallel-combine-primes.cpp
// compile with: /EHsc
#include <windows.h>
#include <ppl.h>
#include <bitset>
#include <iostream>

using namespace concurrency;
using namespace std;

// Calls the provided work function and returns the number of milliseconds 
// that it takes to call that function.
template <class Function>
__int64 time_call(Function&& f)
{
   __int64 begin = GetTickCount();
   f();
   return GetTickCount() - begin;
}

// Determines whether the input value is prime.
bool is_prime(int n)
{
   if (n < 2)
      return false;
   for (int i = 2; i < n; ++i)
   {
      if ((n % i) == 0)
         return false;
   }
   return true;
}

const int limit = 40000;

int wmain()
{
   // A set of prime numbers that is computed serially.
   bitset<limit> primes1;

   // A set of prime numbers that is computed in parallel.
   bitset<limit> primes2;

   __int64 elapsed;

   // Compute the set of prime numbers in a serial loop.
   elapsed = time_call([&] 
   {
      for(int i = 0; i < limit; ++i) {
         if (is_prime(i))
            primes1.set(i);
      }
   });
   wcout << L"serial time: " << elapsed << L" ms" << endl << endl;

   // Compute the same set of numbers in parallel.
   elapsed = time_call([&] 
   {
      // Use a parallel_for loop and a combinable object to compute 
      // the set in parallel. 
      // You do not need to synchronize access to the set because the 
      // combinable object provides a separate bitset object to each thread.
      combinable<bitset<limit>> working;
      parallel_for(0, limit, [&](int i) {
         if (is_prime(i))
            working.local().set(i);
      });

      // Merge each thread-local computation into the final result.
      working.combine_each([&](bitset<limit>& local) {
         primes2 |= local;
      });
   });
   wcout << L"parallel time: " << elapsed << L" ms" << endl << endl;
}

프로세서가 4개인 컴퓨터의 샘플 출력은 다음과 같습니다.

serial time: 312 ms

parallel time: 78 ms

코드 컴파일

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

cl.exe /EHsc parallel-combine-primes.cpp

참고 항목

병렬 컨테이너 및 개체
combinable 클래스
combinable::combine_each 메서드