프로그래밍/Parallel Programming

병렬 프로그래밍 Parallel Programming - parallel_for

nanze 2021. 12. 22. 22:44
반응형

이전 정리글은

2021.12.20 - [프로그래밍/Parallel Programming] - 병렬 프로그래밍 Parallel Programming - task_group

 

4번째 병렬 프로그래밍 관련 정리 시간이다. 오늘은 PPL 에서 제공하는 함수 중 parallel_for 에 대해서 알아보자.!

parallel_for

 parallel_for 함수는 인자의 함수가 수행하는 작업이 병렬적으로 수행된다고 생각하면 된다. 몇 개의 스레드가 ? 몇 구간을 나눠서 ? 이런 것은 생각할 필요가 없다. 내부 구현부에서 최적화된 방식으로 작업을 수행한다고 한다. 음.. 이 함수가 쓰이는 곳은 병렬적으로 이루어져야 하는 작업이 데이터를 공유하지 않고 수행될 수 있을 때 유리할 것 같다. 자 코드를 보자.

#include <ppl.h>
#include <array>
#include <iostream>

using namespace std;

int _tmain()
{
    array< array<int, 9>, 9> gugumatrix;
    concurrency::parallel_for(1, 10, [&](int i)
        {
            concurrency::parallel_for(1, 10, [&](int j)
                {
                    gugumatrix[i-1][j-1] = i*j;
                }
            );
        }
    );
    
    for(auto it = gugumatrix.begin(); it != gugumatrix.end(); it++){
        for(auto it_ = it->begin(); it_ != it->end(); it_++){
            wcout << *it_ << L"\t";
        }
        wcout << endl;
    }
    
    return 0;
}

 위 코드를 보면 gugumatrix 이차원 배열에 곱셉의 결과를 넣고 있다. 여기서 중요한 것은 일반적인 for 와 달리 곱셉이 진행되는 순서는 매 실행시마다 다르다는 것이다. 하지만 for 구문과 비교하여 대상 곱의 범위가 클 경우 parallel_for 함수가 훨~~~~씬 빠르게 끝난다. 한번 해보시라. ㅋ,.ㅋ  parallel_for 함수는 두 개의 오버로드 버전을 제공한다. 

template < typename _Index_type, typename _Function >
_Function parallel_for( _Index_type _First,  _Index_type _Last, _Function _Func );
/*
_Index_type _First : 시작 위치
_Index_type _Last : 종료 위치
_Function _Func : 병렬 처리 함수
*/
template < typename _Index_type, typename _Function >
_Function parallel_for( _Index_type _First, _Index_type _Last, _Index_type _Step, _Function _Func );
/*
_Index_type _First : 시작 위치
_Index_type _Last : 종료 위치
_Index_type _Step : 증가 값 음수가 될 수 없음!!
_Function _Func : 병렬 처리 함수
*/

 이 함수를 사용할 경우 유의해야할 점이 하나 있다. 종료 위치 인덱스에 대해서 착오가 있으면 안된다. 예를 들어 for(int i =0; i <10; i++) 에 대응하는 parallel_for 의 시작, 종료 인덱스 값은 0 과 10 이다. ~!

 어제 부스트샷을 맞았더니 상태가 메롱이다.  다음은 parallel_for_each 간단하게 알아보고 쉬어야겠다. 

parallel_for_each

parallel_for_each 함수는 전자와 동일한 기능이나 쓰임새가 for_each 와 같다고 생각하면 된다.

#include <ppl.h>
#include <array>
#include <iostream>

using namespace std;

int _tmain()
{
    vector<int> vec;
    for(int i=0;i<30;i++){
       vec.push(i);
    }
    
    concurrency::parallel_for_each(begin(vec), end(vec), [](int n)
        {
            wcout << n << endl;
        }
    );
    
    return 0;
}

 위 코드를 실행해보면 중구난방으로 숫자가 찍힐 것이다. 왜냐~! 실행의 순서를 보장하지 않기 때문이다. ㅋ,.ㅋ

 다음 정리는 내일로 미루어야 겠다. 좋은 밤 모든 사람이 행복하기를 바라면서. 

 

다음 정리글은

2021.12.26 - [프로그래밍/Parallel Programming] - 병렬 프로그래밍 Parallel Programming - parallel_invoke

반응형