Note: this is NOT a duplicate of this quesiton.
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);
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.
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
I hope TBB/Intel experts can recommend a better solution, thank you!
tbb::global_control
example itself uses "deprecated"task_scheduler_init
? The old forum thread you refer to actually was the source of my original sample code. But as stated in the question, it creates threads nonetheless. – Nurserymaid