non*_*one 3 c++ multithreading loops tbb
我发现英特尔的Thread Building Blocks库令人困惑.例如,我想使用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;
}
Run Code Online (Sandbox Code Playgroud)
我知道你必须operator()在TBB中使用一个类来做到这一点; 真的吗?我本来希望在TBB上阅读一些"初学者教程",以帮助我解决这个问题,但似乎没有任何初学者教程.
你能帮我把TBB应用到这个计算中吗?
TBB有一个帮助参考文档,对于入门非常有用.使用该文档的parallel_for,它很简单,你的例子转换成使用parallel_for时.下面是一些示例代码.这不是100%,但你可以得到这个想法.上面的链接也包含一些更有趣的功能的示例.
#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;
}
Run Code Online (Sandbox Code Playgroud)