Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TBB tutorial/documentation for parallelizing my code? [closed]

I am finding Intel's Thread Building Blocks library kind of confusing. For instance, I want to parallelize the following computation using TBB:

int CountNegatives(std::vector<Trigraph> input)
{
    int count = 0;
    for(int i = 0; i< input.size(); i++)
    {
        if(input[i].VisibleFrom(viewPoint))
        {
            count++;
        }
    }
    return count;
}

I understand you have to use an operator() with a class to do that in TBB; is that true? I would have liked to read some "beginner's tutorial" on TBB to help me figure this out, but there don't seem to be any beginner tutorials around.

Can you help me apply TBB to this computation at least?

like image 675
none Avatar asked Aug 26 '26 07:08

none


1 Answers

TBB has a help reference doc that is pretty useful to get started. Using the doc for parallel_for, its pretty simple to convert your example into using parallel_for. Below is some sample code. It's not 100%, but you can get the idea. The link above contains examples for some of the more interesting functionality too.

#include <tbb/parallel_for.h>
#include <tbb/atomic.h>
#include <iostream>
#include <vector>

/** 
 * To be used with tbb::parallel_for, this increments count
 * if the value at the supplied index is zero.
 */
class ZeroCounter
{
public:
    ZeroCounter(std::vector<int> * vec, tbb::atomic<int> * count) :
        vec(vec),
        count(count)
    { } 

    void operator()(int index) const
    {
        if((*vec)[index] == 0)
            ++(*count);
    }

    std::vector<int> * vec;
    tbb::atomic<int> * count;
};

int main()
{
    // Create a vector and fill it with sample values
    std::vector<int> a;
    a.push_back(0);
    a.push_back(3);
    a.push_back(0);

    // Counter to track the number of zeroes
    tbb::atomic<int> count;
    count = 0;

    // Create our function object and execute the parallel_for
    ZeroCounter counter(&a, &count);
    tbb::parallel_for(size_t(0), a.size(), counter);

    std::cout << count << std::endl;
}
like image 91
JaredC Avatar answered Aug 28 '26 00:08

JaredC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!