Reputation: 1903
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!
Upvotes: 6
Views: 3385
Reputation: 3937
For posterity,
#include <tbb/global_control.h>
// somewhere
tbb::global_control c(tbb::global_control::max_allowed_parallelism, 1);
https://spec.oneapi.com/versions/0.5.0/oneTBB/task_scheduler/tbb_global_control.html
Upvotes: 5
Reputation: 41
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.
Upvotes: 4