注意:这不是这个问题的重复。
给定一个与 TBB 并行的复杂软件,我如何完全关闭线程?我知道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);
Run Code Online (Sandbox Code Playgroud)
但是,此解决方案(与此相关)不会关闭线程。TBB 仍然会创建大量线程,nthreads只是使其中一些线程未被使用。此外,如果有nthreads = 1,TBB 实际上会创建 1 个额外的线程 - 加上主线程总共 2 个线程。
是的,在某些情况下,您确实希望完全关闭线程,但仍保持 TBB 代码处于活动状态。我当前的解决方案是对 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) { …Run Code Online (Sandbox Code Playgroud)