【发布时间】:2015-01-15 03:39:57
【问题描述】:
有人告诉我 enumerable_thread_specific 会提高线程性能,但我不明白为什么。使用英特尔线程构建模块 (TBB) 库中的enumerable_thread_specific 有什么好处?
文档 (link) 的动机有些模糊,但似乎表明它的目的是在您不知道提前线程数的情况下在列表中懒惰地创建项目,如 TBB 文档示例中所示在链接中:
#include <cstdio>
#include <utility>
#include "tbb/task_scheduler_init.h"
#include "tbb/enumerable_thread_specific.h"
#include "tbb/parallel_for.h"
#include "tbb/blocked_range.h"
using namespace tbb;
typedef enumerable_thread_specific< std::pair<int,int> > CounterType;
CounterType MyCounters (std::make_pair(0,0));
struct Body {
void operator()(const tbb::blocked_range<int> &r) const {
CounterType::reference my_counter = MyCounters.local();
++my_counter.first;
for (int i = r.begin(); i != r.end(); ++i)
++my_counter.second;
}
};
int main() {
parallel_for( blocked_range<int>(0, 100000000), Body());
for (CounterType::const_iterator i = MyCounters.begin();
i != MyCounters.end(); ++i)
{
printf("Thread stats:\n");
printf(" calls to operator(): %d", i->first);
printf(" total # of iterations executed: %d\n\n",
i->second);
}
}
这真的有必要吗?还有没有列出的其他好处?有人指出跨线程访问内存可能有优势,但我不清楚这是怎么发生的?
【问题讨论】:
标签: c++ multithreading tbb