【问题标题】:TLS enumerable_thread_specific in TBBTBB 中的 TLS enumerable_thread_specific
【发布时间】: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


    【解决方案1】:

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

    通常,TLS 允许避免线程之间争用处理器缓存或互斥锁,否则共享全局对象会发生这种争用。有关类似容器 combinable&lt;&gt; 的更多详细信息和解释,请参阅 this blog,该容器也可在 TBB 中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多