간단한 TBB  parallel_for  예제  

여기서는 람다를 사용을 하고 있지만...

아직 C++0x가 적용 안된 컴파일러 (Windows의 경우 visual studio 2008 이하) 는 람다 함수를 사용 할 수가 없다.

람다 함수를 사용하는 대신에 functor를 이용 해야 한다.

[-] Collapse  

#include <stdio.h>
#include <tchar.h>
#include <tbb/task_scheduler_init.h>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include <tbb/atomic.h> // atomic
#include <tbb/mutex.h> // 뮤텍스



#ifdef _DEBUG
#pragma  comment(lib, "tbb_debug.lib")
#else
#pragma  comment(lib, "tbb.lib")
#endif // _DEBUG



using namespace tbb ;

int main(int argc, _TCHAR* argv[])
{
    task_scheduler_init init ;

    //int nOut = 0 ;
    atomic<int> nOut ;
    nOut  = 0 ;


    parallel_for(blocked_range<int>(0, 100000),
        [&nOut](const blocked_range<int>& iter)
    {
        for (int n = iter.begin() ; n != iter.end() ; ++n)
        {
            nOut += 1 ;
        }
    }
    ,  auto_partitioner()) ;

    printf("Result %d\n", nOut) ;



    // 다른 락거는 방법

    tbb::mutex _lock;
    int   _sum = 0;
    parallel_for(blocked_range<int>(0, 100000),
        [&_lock, &_sum](const blocked_range<int>& iter)
    {
        int sum = 0;
        for (int n = iter.begin() ; n != iter.end() ; ++n)
        {
            sum += 1 ;
        }

        _lock.lock() ;
        _sum += sum ;
        _lock.unlock() ;
    },  auto_partitioner()) ;

    printf("Result2 : %d\n", _sum) ;

    getchar() ;
    return 0;
}

'C++ > Intell C++' 카테고리의 다른 글

간단한 TBB parallel_reduce 예제  (0) 2014.09.16
간단한 TBB parallel_while 예제  (0) 2014.09.16
간단한 TBB parallel_sort 예제  (0) 2014.09.16
간단한 TBB parallel_invoke 예제  (1) 2014.09.16

parallel_for문과는 달리  합산 및 정산을 할때 동기화 이슈가 없다.

각각 쓰레드 별로  body 객체가 생성이 되고  연산후

join문에서 합산되기때문이다.

 

 

[-] Collapse
#include <stdio.h>
#include <tchar.h>
#include <tbb/tbb.h>


#ifdef _DEBUG
#pragma  comment(lib, "tbb_debug.lib")
#else
#pragma  comment(lib, "tbb.lib")
#endif // _DEBUG

using namespace tbb;

class CSumBody
{
public:
    CSumBody()
    {
        sum_ = 0 ;
    }

    CSumBody(CSumBody &body, split)
    {
        sum_ = 0 ;
    }

    void operator()(const tbb::blocked_range<__int64> &iter)
    {
        for (__int64 n = iter.begin() ; n != iter.end() ; ++n)
        {
            sum_ += 1 ;
        }
    }

    void join(const CSumBody &body)
    {
        sum_ += body.sum_ ;
    }
public:
    __int64 sum_ ;
};



int _tmain(int argc, _TCHAR* argv[])
{

    tick_count start,stop;
    __int64 sum = 0 ;
    task_scheduler_init  init ;


    start = tick_count::now();

    CSumBody body ;
    parallel_reduce(blocked_range<__int64>(0, 1000000000), body, auto_partitioner()) ;


    stop = tick_count::now();
    printf("Result %d  \t시간 %f\n", body.sum_, (stop - start).seconds()) ;

    getchar() ;
    return 0;
}






'C++ > Intell C++' 카테고리의 다른 글

간단한 TBB parallel_for 예제  (0) 2014.09.16
간단한 TBB parallel_while 예제  (0) 2014.09.16
간단한 TBB parallel_sort 예제  (0) 2014.09.16
간단한 TBB parallel_invoke 예제  (1) 2014.09.16

범위를 알 수 없을 때 사용하는 while문을 병렬화 시킨 로직이다.

그리고 type은 정해져 있지 않으므로 포인터를 이용하여 리스트 자료구조를  순회를 할때도 문제 없다

 

 

 

[-] Collapse
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <tbb/tbb.h>
#include <tbb/parallel_while.h>

#ifdef _DEBUG
#pragma  comment(lib, "tbb_debug.lib")
#else
#pragma  comment(lib, "tbb.lib")
#endif // _DEBUG

using namespace tbb;

class CItemStream
{
public:
    CItemStream(int n) : num(n) {}

    // 여기서는 카운터 연산만 처리 해야함... 여기에서는 동기화 이슈가 없음
    bool pop_if_present(int &count)
    {
        // 언제 끝날지 모르게 하기 위해서 rand 함수를 사용
        // 실제로 count를 이용할 경우에는  if (func(num) == 0) 등등 꼴리는데로 사용!!!
        if(!(rand() % 10  != 0))
        {
            printf("루프종료...\n") ;
            return false ;
        }
        printf("Count %d\n", num) ;
        count = num ;
        num++ ;
        return true ;
    }
public:
    int num ;
};

class CBody
{
public:
    // 실제로 자료에 대한 처리는 여기서 해야 함
    void operator()(int n) const
    {
        printf("count : %d에 대한 처리 \n", n ) ;
    }
    typedef int argument_type ;
};

int _tmain(int argc, _TCHAR* argv[])
{
    srand((unsigned int)time(0)) ;
    // 아래 직렬로직을  TBB로 병렬화 루틴...
    // 단 카운트가 순서대로 처리 되지 않는다.

// int num = 0 ;
// while (rand() % 10 == 0 )
// {
// printf("count : %d에 대한 처리 \n", num ) ;
// num++ ;
// }


    parallel_while<CBody> w ;
    CItemStream stream_(0) ;
    CBody body ;

    w.run(stream_, body) ;
    printf("루프 끝\n") ;


    getchar() ;
    return 0;
}

'C++ > Intell C++' 카테고리의 다른 글

간단한 TBB parallel_for 예제  (0) 2014.09.16
간단한 TBB parallel_reduce 예제  (0) 2014.09.16
간단한 TBB parallel_sort 예제  (0) 2014.09.16
간단한 TBB parallel_invoke 예제  (1) 2014.09.16

병렬 처리 쓰레드로 정렬을 한다. 

정렬할 데이터가 많고 CPU 코어 갯수가 높을 수록 일반 sort보다 많이 빨라지게 된다.

parallel_while이나 다른 알고리즘에 비해 아주 간단하게 쓸 수 있다.. -ㅅ-...

 

여기서는 람다를 사용을 하고 있지만...

아직 C++0x가 적용 안된 컴파일러 (Windows의 경우 visual studio 2008 이하) 는 람다 함수를 사용 할 수가 없다.

람다 함수를 사용하는 대신에 functor를 이용 해야 한다.

 

 

[-] Collapse
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <tbb/tbb.h>

#ifdef _DEBUG
#pragma  comment(lib, "tbb_debug.lib")
#else
#pragma  comment(lib, "tbb.lib")
#endif // _DEBUG

using namespace tbb ;

class CNObject
{
public:
    bool operator<(const CNObject & t) const
    {
        return  (data < t.data) ;
    }
public:
    int data ;
    char dumy ;
};

int _tmain(int argc, _TCHAR* argv[])
{
    task_scheduler_init init ;
    srand((unsigned int)time(NULL)) ;
    printf("병렬 처리 정렬 알고리즘\n") ;

    // 정렬을 테스트를 위한 데이터 생성
    CNObject aValue[10] ;
    for (int n = 0 ; n < 10 ; ++n )
    {
        aValue[n].data = rand() % 10 ;
        printf("%d ", aValue[n].data) ;
    }
    printf("\n") ;

    // 연산자 오버로딩을 이용한 연산
    parallel_sort(aValue, aValue + 10 ) ;

    for (int n = 0  ; n < 10 ; ++n )
    {
        printf("%d ", aValue[n].data) ;
    }
    printf("\n") ;

    // 이번엔 람다를 이용해서 정렬
    parallel_sort(aValue, aValue + 10,
        [](const CNObject &t1, const CNObject &t2)->bool
    {
        return (t1.data > t2.data);
    }) ;

    for (int n = 0  ; n < 10 ; ++n )
    {
        printf("%d ", aValue[n].data) ;
    }
    printf("\n") ;

    getchar() ;
    return 0;
}


'C++ > Intell C++' 카테고리의 다른 글

간단한 TBB parallel_for 예제  (0) 2014.09.16
간단한 TBB parallel_reduce 예제  (0) 2014.09.16
간단한 TBB parallel_while 예제  (0) 2014.09.16
간단한 TBB parallel_invoke 예제  (1) 2014.09.16

여러 루틴이 순서와 상관 없이 병렬로 실행되게 하고 싶을때 사용을 한다.

 

parallel_invoke 루틴은 반환할때는 모든 처리 루틴이 전부 동작되고 난 다음에야 리턴이 된다.

 

총 9개 까지 람다식 및 functor가 등록 될 수 있다.

 

 

[-] Collapse
#include <stdio.h>
#include <tchar.h>
#include <time.h>
#include <tbb/tbb.h>

#ifdef _DEBUG
#pragma  comment(lib, "tbb_debug.lib")
#else
#pragma  comment(lib, "tbb.lib")
#endif // _DEBUG

using namespace tbb ;



int _tmain(int argc, _TCHAR* argv[])
{
    task_scheduler_init init ;
    parallel_invoke(
        []() -> void
    {
        ::Sleep(1000);
        ::printf("finish : %d\n", 1000);
    },
        []() -> void
    {
        ::Sleep(10000);
        ::printf("finish : %d\n", 10000);
    }) ;

    printf("모든 작업 종료 \n") ;

    getchar() ;
    return 0;
}

'C++ > Intell C++' 카테고리의 다른 글

간단한 TBB parallel_for 예제  (0) 2014.09.16
간단한 TBB parallel_reduce 예제  (0) 2014.09.16
간단한 TBB parallel_while 예제  (0) 2014.09.16
간단한 TBB parallel_sort 예제  (0) 2014.09.16

+ Recent posts