TBB:如何在代码的不同部分设置不同数量的线程?



我有一个tbb::task_scheduler_init实例init它用我无法控制的代码部分中的某些一定数量的线程初始化,在后面的代码部分中,我想使用不同数量的线程运行。如何通过此实例init执行此操作?

有没有比执行以下操作更好的方法?

init.terminate();
init.initialize(my_preferred_number_of_threads);
/*
run some code
*/
init.terminate();
init.initialize(original_number_of_threads); // restore the original tbb scheduler

您可以使用 tbb::task_arena 来满足自己的需求。

摘自 tbb::task_arena 文档

tbb::task_scheduler_init def_init; // Use the default number of threads.
tbb::task_arena limited(2);        // No more than 2 threads in this arena.
tbb::task_group tg;
limited.execute([&]{ // Use at most 2 threads for this job.
tg.run([]{ // run in task group
tbb::parallel_for(1, N, unscalable_work());
});
});
// Run another job concurrently with the loop above.
// It can use up to the default number of threads.
tbb::parallel_for(1, M, scalable_work());
// Wait for completion of the task group in the limited arena.
limited.execute([&]{ tg.wait(); });

最新更新