gpt4 book ai didi

c++ - TBB 中的 TLS enumerable_thread_specific

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:42:01 25 4
gpt4 key购买 nike

有人告诉我 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);
}
}

这真的有必要吗?还有没有列出的其他好处吗?有人指出跨线程内存访问可能有优势,但我不清楚这是怎么发生的?

最佳答案

enumerable_thread_specific 的想法是围绕 TLS 的概念提供一个容器。或 thread_local in C++11这样一个线程分配的值可以稍后在另一个线程中组合/枚举。实际有助于提高性能的是上述概念的共同属性。

通常,TLS 允许避免线程之间对处理器缓存或互斥体的争用,否则共享全局对象会发生争用。参见 this blog有关类似容器的更多详细信息和解释 combinable<>在 TBB 中也可用。

关于c++ - TBB 中的 TLS enumerable_thread_specific,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com