问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/59736661/how-to-completely-switch-off-threading-in-tbb-code