1
我很难理解TBB的可枚举线程特定。 我写了这个小代码来测试TLS关于TBB线程本地存储
#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并不包含所有期望值,但其原因显然是关于父母和孩子任务的关系。虽然不太明白这一点。
任何帮助?
谢谢。
谢谢你的回答,Alexey。我在TBB论坛上的帖子是这样的:software.intel.com/en-us/forums/... 在那里,作者说这个: >然而,问题来了:在粒子碰撞ets中, >当获得b选项时,ets不包含计划的所有碰撞,只包括其中一个孩子的本地数据。 这个问题是否也出现在这里?或者是否因为作者的一些错误代码而发生? – 2012-04-16 16:55:17
我认为TBB论坛帖子的作者误解了一些东西。我在那里回答他,试图澄清他真正想要的并提出一些想法来探索。 – 2012-04-16 22:08:13
好的!谢谢你的帮助Alexey! – 2012-04-17 09:51:50