TBB 学习笔记

#include <tbb/task_scheduler_init.h>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <iostream>

class ApplyFoo
{

private:
    float *const my_a;
public:
    void operator()(const tbb::blocked_range<size_t>&r)const
    {
        float *a=my_a;
        for(int i=r.begin();i!=r.end();++i)
        {
            printf("gevar = %f
",a[i]);
        }
    }
    ApplyFoo(float a[]):   
        my_a(a)
    {
    }
};
void parallelApplyFoo(float a[],size_t n)
{
    tbb::parallel_for ( tbb::blocked_range<size_t> (0,n),ApplyFoo(a) ,tbb::auto_partitioner());
}
int main()
{
    //tbb::task_scheduler_init init;
    float a[10]={1,2,3,4,5,6,7,8,9,10};
    parallelApplyFoo(a,10);
    return 0;
}

修改简化版本:

#include <iostream>
#include <tbb/task_scheduler_init.h>
#include <tbb/blocked_range.h>
#include <tbb/parallel_for.h>
#include <vector>

using namespace std;
using namespace tbb;

#define THREAD_FUNCTION void operator()(const blocked_range<size_t> &r)const
#define THREAD_EXCUTED_FOR(N,CLASS)
{
parallel_for(blocked_range<size_t>(0,N),CLASS,auto_partitioner());
}


class ApplyFoo
{
public:
    ApplyFoo()
    {
    }
    void setData(float *data)
    {
        my_a = data;
    }
    THREAD_FUNCTION
    {
        //cout << "going to thread
";
        float *a = my_a;
        for(size_t i=r.begin();i!=r.end();++i)
        {
            //cout << "going to thread:"<<i<<endl;
            a[i] = 10;
        }
    }
private:
    float * my_a;
};


int main() {

    long int size = 5000000000;
    vector<float> b(size);
    cout << "loop size " << b.size() << endl;
    cout << "start threading
";
    ApplyFoo foo;
    foo.setData(b.data());
    THREAD_EXCUTED_FOR(size,foo);
    cout << "thread executed end
";
    cout << b[0] << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/gearslogy/p/4678913.html