1#ifndef STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP
2#define STAN_MATH_PRIM_CORE_INIT_THREADPOOL_TBB_HPP
6#include <boost/lexical_cast.hpp>
8#ifndef TBB_INTERFACE_NEW
9#include <tbb/tbb_stddef.h>
11#if TBB_VERSION_MAJOR >= 2020
12#define TBB_INTERFACE_NEW
16#ifdef TBB_INTERFACE_NEW
17#include <tbb/global_control.h>
18#include <tbb/task_arena.h>
20#include <tbb/task_scheduler_init.h>
49 const char* env_stan_num_threads = std::getenv(
"STAN_NUM_THREADS");
50 if (env_stan_num_threads !=
nullptr) {
52 const int env_num_threads
53 = boost::lexical_cast<int>(env_stan_num_threads);
54 if (env_num_threads > 0) {
55 num_threads = env_num_threads;
56 }
else if (env_num_threads == -1) {
57 num_threads = std::thread::hardware_concurrency();
61 "The STAN_NUM_THREADS environment variable is '",
62 "' but it must be positive or -1");
64 }
catch (
const boost::bad_lexical_cast&) {
67 "The STAN_NUM_THREADS environment variable is '",
68 "' but it must be a positive number or -1");
77#ifdef TBB_INTERFACE_NEW
101 int tbb_max_threads = 1;
103 if (n_threads == 0) {
105 }
else if (n_threads > 0) {
106 tbb_max_threads = n_threads;
107 }
else if (n_threads == -1) {
108 tbb_max_threads = std::thread::hardware_concurrency();
111 "The number of threads is '",
112 "' but it must be positive or -1");
115 static tbb::global_control tbb_gc(
116 tbb::global_control::max_allowed_parallelism, tbb_max_threads);
117 static tbb::task_arena tbb_arena(tbb_max_threads, 1);
118 tbb_arena.initialize();
146 int tbb_max_threads = 1;
148 if (n_threads == 0) {
150 }
else if (n_threads > 0) {
151 tbb_max_threads = n_threads;
152 }
else if (n_threads == -1) {
153 tbb_max_threads = std::thread::hardware_concurrency();
156 "The number of threads is '",
157 "' but it must be positive or -1");
160 static tbb::task_scheduler_init tbb_scheduler(tbb_max_threads, 0);
161 return tbb_scheduler;
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 ...