tbb - 关于TBB线程本地存储

标签 tbb thread-local-storage

我很难理解 TBB 的可枚举线程特定。 我编写了这段小代码来测试 TLS

#include <iostream>
#include <vector>

#include "tbb/task_scheduler_init.h"
#include "tbb/enumerable_thread_specific.h"
#include "tbb/task.h"

typedef tbb::enumerable_thread_specific< std::vector<int> > TLS;

class Child: public tbb::task {
private:
  int start;
  int limit;
  TLS* local_tls;
public:
  Child( int s_, int l_, TLS* t_):start(s_),limit(l_),local_tls(t_){}
  virtual ~Child(){ 
    local_tls=0;
  }
  tbb::task* execute(){
   TLS::reference local_vector = local_tls->local();
   for(int i=start; i<limit;++i){
   local_vector.push_back( i );
   }
  }
  return 0;
 }
};

class Cont: public tbb::task {
private:
  TLS global_tls;
public:
  Cont(){}
  virtual ~Cont(){}
  TLS* GetTls(void) { return &global_tls; }
  tbb::task* execute(){
    TLS::const_iterator it( global_tls.begin() );
    const TLS::const_iterator end( global_tls.end() );
    std::cout << "ETS.SIZE: " << global_tls.size() << std::endl;
    while( it != end ) {
      std::cout << "*ITSIZE: " << (*it).size() << "\n";
      for( unsigned int j(0); j < (*it).size(); ++j ) {
        std::cout << (*it)[j] << " " << std::endl;
      }  
      ++it;
    }
    return 0;
  }
};

class Root: public tbb::task {
private:
public:
  Root(){}
  virtual ~Root(){}
  tbb::task* execute(){
    tbb::task_list l;
    Cont& c = *new ( allocate_continuation() ) Cont();
    l.push_back( (*new ( c.allocate_child() ) Child(0,10,c.GetTls()) ) );
    l.push_back( (*new ( c.allocate_child() ) Child(11,21,c.GetTls()) ) );
    c.set_ref_count( 2 );
    c.spawn( l );
    return 0;
  }
};

int main(void) {
  Root& r = *new(tbb::task::allocate_root()) Root( );
  tbb::task::spawn_root_and_wait( r ); 
  return 0;
}

但是输出很尴尬。有时是:

ETS.SIZE: 2
*ITSIZE: 10
0 1 2 3 4 5 6 7 8 9 
*ITSIZE: 10
11 12 13 14 15 16 17 18 19 20

有时是:

ETS.SIZE: 1
*ITSIZE: 20
0 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20

为什么会发生这种变化? 另外,在 TBB 论坛中,我读到有时 TLS 不包含所有预期值,但其原因显然是有关父任务和子任务的关系。不过不太明白。

有什么帮助吗?

谢谢。

最佳答案

您看到的“尴尬”输出差异与enumerable_thread_specific无关。这只是由于 Child 任务由两个不同的线程(在情况 1 中)或同一线程(在情况 2 中)执行。

关于tbb - 关于TBB线程本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10164598/

相关文章:

c++ - 使用线程构建 block (TBB) 时如何修改线程调度行为?

c++ - PPL when_all 具有不同类型的任务?

c# - 重复调用CurrentThread.ManagedThreadId或将值存储在线程本地存储中?

c++ - 如何重新安排并发任务?

c++ - 如何在 OSX 上获取 tbbmalloc_proxy?

wcf - 将 OperationContext.Current 存储在 WCF 服务实例的实例变量中

java - 使用 ThreadLocalTargetSource 填充的 Autowiring 对象不会为每个类填充

c++ - TLS 变量上的 "illegal thread-local reference to regular symbol"错误

python - 在 python 程序中通过 ctypes 使用具有线程本地存储的共享库时发生内存泄漏

c++ - 包括 <execution> 需要链接到 tbb 吗?