1#ifndef STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP
2#define STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP
6#ifndef TBB_INTERFACE_NEW
7#include <tbb/tbb_stddef.h>
9#if TBB_VERSION_MAJOR >= 2020
10#define TBB_INTERFACE_NEW
14#ifdef TBB_INTERFACE_NEW
15#include <tbb/global_control.h>
16#include <tbb/task_arena.h>
18#include <tbb/task_scheduler_init.h>
48 const char* env_stan_num_threads = std::getenv(
"STAN_NUM_THREADS");
49 if (env_stan_num_threads ==
nullptr) {
53 const std::string_view value(env_stan_num_threads);
55 const auto [end, error]
56 = std::from_chars(value.begin(), value.end(), num_threads);
57 if (error != std::errc() || end != value.end()
58 || (num_threads < 1 && num_threads != -1)) {
61 "The STAN_NUM_THREADS environment variable is '",
62 "' but it must be a positive number or -1");
65 return num_threads == -1 ? std::thread::hardware_concurrency() : num_threads;
71#ifdef TBB_INTERFACE_NEW
78 :
control(tbb::global_control::max_allowed_parallelism, num_threads),
79 arena(num_threads, 1) {
92#ifdef TBB_INTERFACE_NEW
115 int tbb_max_threads = 1;
117 if (n_threads == 0) {
119 }
else if (n_threads > 0) {
120 tbb_max_threads = n_threads;
121 }
else if (n_threads == -1) {
122 tbb_max_threads = std::thread::hardware_concurrency();
125 "The number of threads is '",
126 "' but it must be positive or -1");
130 state.arena.initialize();
158 int tbb_max_threads = 1;
160 if (n_threads == 0) {
162 }
else if (n_threads > 0) {
163 tbb_max_threads = n_threads;
164 }
else if (n_threads == -1) {
165 tbb_max_threads = std::thread::hardware_concurrency();
168 "The number of threads is '",
169 "' but it must be positive or -1");
172 static tbb::task_scheduler_init tbb_scheduler(tbb_max_threads, 0);
173 return tbb_scheduler;
threadpool_tbb_state make_threadpool_tbb(int num_threads)
Construct independently owned thread-pool state for an explicit count.
int get_num_threads()
Get number of threads to use.
tbb::task_arena & init_threadpool_tbb(int n_threads=0)
Initialize the Intel TBB threadpool and global scheduler through the tbb::task_arena object.
void invalid_argument(const char *function, const char *name, const T &y, const char *msg1, const char *msg2)
Throw an invalid_argument exception with a consistently formatted message.
The lgamma implementation in stan-math is based on either the reentrant safe lgamma_r implementation ...
tbb::global_control control
threadpool_tbb_state(int num_threads)
Own the concurrency control before the arena, so the arena dies first.