问题描述
注意:这不是此问题的重复.
Note: this is NOT a duplicate of this quesiton.
给定与TBB并行运行的复杂软件,我如何完全关闭线程处理?我知道task_scheduler_init:
Given a complex software parallelized with TBB, how do I completely switch off threading? I'm aware of the task_scheduler_init:
int nthreads = tbb::task_scheduler_init::default_num_threads();
const char* cnthreads = getenv("TBB_NUM_THREADS");
if (cnthreads) nthreads = std::max(1, atoi(cnthreads));
tbb::task_arena arena(nthreads, 1);
tbb::task_scheduler_init init(nthreads);
但是,此解决方案(与此有关)不会关闭线程. TBB仍然创建许多线程,nthreads
只是使其中一些不被使用.此外,如果其中一个具有nthreads = 1
,则TBB实际上会创建1个额外的线程-与主线程一起总共2个线程.
However, this solution (related to this) does not switch off threading. TBB still creates lots of threads, nthreads
just makes some of them not being used. Moreover, if one has nthreads = 1
, TBB actually creates 1 extra thread - totaling 2 threads together with master thread.
是,在某些情况下,您确实希望完全关闭线程功能,但仍要保留TBB代码.我当前的解决方案是在tbb周围草率包装:
Yes, there are certain situations when you'd want to really switch off threading completely, yet keeping the TBB code alive. My current solution is a sloppy wrapper around tbb:
namespace hddm {
bool enableTBB = true;
class task_group {
unique_ptr<tbb::task_group> tbb;
public :
task_group() {
if (enableTBB)
tbb.reset(new tbb::task_group());
}
template<typename F>
void run(const F& f) {
if (tbb)
tbb->run(f);
else
f();
}
void wait() {
if (tbb)
tbb->wait();
}
};
class task_arena {
unique_ptr<tbb::task_arena> tbb;
public :
task_arena(int nthreads, int dedicated) {
if (enableTBB)
tbb.reset(new tbb::task_arena(nthreads, dedicated));
}
template<typename F>
void execute(const F& f) {
if (tbb)
tbb->execute(f);
}
};
class task_scheduler_init {
unique_ptr<tbb::task_scheduler_init> tbb;
public :
task_scheduler_init(int nthreads) {
if (enableTBB)
tbb.reset(new tbb::task_scheduler_init(nthreads));
}
};
class parallel_for {
public :
template<typename F>
parallel_for(const tbb::blocked_range<int>& r, const F& f) {
if (enableTBB)
tbb::parallel_for(r, f);
else
f(r);
}
};
} // namespace hddm
我希望TBB/英特尔专家可以推荐更好的解决方案,谢谢!
I hope TBB/Intel experts can recommend a better solution, thank you!
推荐答案
自Intel TBB 4.3 Update 5(参见文档和此论坛主题).现在,您可以在全局变量上使用 tbb :: global_control 类来修改此行为范围.
Using tbb::task_scheduler_init
has been deprecated since Intel TBB 4.3 Update 5 (see Documentation and this forum thread). You can now modify this behavior using the tbb::global_control class on a global scope.
这篇关于如何完全关闭TBB代码中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!