TBB 有一个帮助参考文档,对入门非常有用。使用doc for 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;
}