Python helpers to limit the number of threads used in native libraries that handle their own internal threadpool (BLAS and OpenMP implementations)
Repo joblib/threadpoolctl, read from GitHub 14 min ago. joblib has not joined Take My Repo.
joblib/threadpoolctl is a public repo on GitHub by joblib. Python helpers to limit the number of threads used in native libraries that handle their own internal threadpool (BLAS and OpenMP implementations). It declares the BSD-3-Clause license on GitHub. It is written mainly in Python, has 439 stars and last changed on 2026-11-23. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-24.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
Python helpers to limit the number of threads used in the threadpool-backed of common native libraries used for scientific computing and data science (e.g. BLAS and OpenMP).
Fine control of the underlying thread-pool size can be useful in workloads that involve nested parallelism so as to mitigate oversubscription issues.
Note that "limiting the number of threads" in practice involves a variety of potential semantics depending on the underlying third-party library; see the section on semantics below.
For users, install the last published version from PyPI:
pip install threadpoolctl
For contributors, install from the source repository in developer mode:
pip install -r dev-requirements.txt
flit install --symlink
then you run the tests with pytest:
pytest
Get a JSON description of thread-pools initialized when importing python packages such as numpy or scipy for instance:
python -m threadpoolctl -i numpy scipy.linalg
[
{
"filepath": "/home/ogrisel/miniconda3/envs/tmp/lib/libmkl_rt.so",
"prefix": "libmkl_rt",
"user_api": "blas",
"internal_api": "mkl",
"version": "2019.0.4",
"num_threads": 2,
"threading_layer": "intel"
},
{
"filepath": "/home/ogrisel/miniconda3/envs/tmp/lib/libiomp5.so",
"prefix": "libiomp",
"user_api": "openmp",
"internal_api": "openmp",
"version": null,
"num_threads": 4
}
]
The JSON information is written on STDOUT. If some of the packages are missing, a warning message is displayed on STDERR.
Introspect the current state of the threadpool-enabled runtime libraries that are loaded when importing Python packages:
>>> from threadpoolctl import threadpool_info
>>> from pprint import pprint
>>> pprint(threadpool_info())
[]
>>> import numpy
>>> pprint(threadpool_info())
[{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libmkl_rt.so',
'internal_api': 'mkl',
'num_threads': 2,
'prefix': 'libmkl_rt',
'threading_layer': 'intel',
'user_api': 'blas',
'version': '2019.0.4'},
{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libiomp5.so',
'internal_api': 'openmp',
'num_threads': 4,
'prefix': 'libiomp',
'user_api': 'openmp',
'version': None}]
>>> import xgboost
>>> pprint(threadpool_info())
[{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libmkl_rt.so',
'internal_api': 'mkl',
'num_threads': 2,
'prefix': 'libmkl_rt',
'threading_layer': 'intel',
'user_api': 'blas',
'version': '2019.0.4'},
{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libiomp5.so',
'internal_api': 'openmp',
'num_threads': 4,
'prefix': 'libiomp',
'user_api': 'openmp',
'version': None},
{'filepath': '/home/ogrisel/miniconda3/envs/tmp/lib/libgomp.so.1.0.0',
'internal_api': 'openmp',
'num_threads': 4,
'prefix': 'libgomp',
'user_api': 'openmp',
'version': None}]
In the above example, numpy was installed from the default anaconda channel and comes
with MKL and its Intel OpenMP (libiomp5) implementation while xgboost was installed
from pypi.org and links against GNU OpenMP (libgomp) so both OpenMP runtimes are
loaded in the same Python program.
The state of these libraries is also accessible through the object oriented API:
>>> from threadpoolctl import ThreadpoolController, threadpool_info
>>> from pprint import pprint
>>> import numpy
>>> controller = ThreadpoolController()
>>> pprint(controller.info())
[{'architecture': 'Haswell',
'filepath': '/home/jeremie/miniconda/envs/dev/lib/libopenblasp-r0.3.17.so',
'internal_api': 'openblas',
'num_threads': 4,
'prefix': 'libopenblas',
'threading_layer': 'pthreads',
'user_api': 'blas',
'version': '0.3.17'}]
>>> controller.info() == threadpool_info()
True
There are two scenarios in which you might want to use threadpoolctl; each
requires you to use different APIs.
This section will cover the former case, and the latter is covered in the next usage section.
Control the number of threads used by the underlying runtime libraries in specific sections of your Python program:
>>> from threadpoolctl import threadpool_limits
>>> import numpy as np
>>> with threadpool_limits(limits=1, user_api='blas'):
... # In this block, calls to blas implementation (like openblas or MKL)
... # will be limited to use only one thread. They can thus be used jointly
... # with thread-parallelism.
... a = np.random.randn(1000, 1000)
... a_squared = a @ a
The threadpools can also be controlled via the object oriented API, which is
especially useful to avoid searching through all the loaded shared libraries
each time. That is, you can reuse a ThreadpoolController to reduce performance
overhead. However, note that it will not act on libraries loaded after the
instantiation of the ThreadpoolController!
>>> from threadpoolctl import ThreadpoolController
>>> import numpy as np
>>> controller = ThreadpoolController()
>>> with controller.limit(limits=1, user_api='blas'):
... a = np.random.randn(1000, 1000)
... a_squared = a @ a
As a compromise between speed and catching newly loaded controllable libraries
you can use get_cached_controller(). This will notice any newly loaded
libraries triggered by importing new libraries, but might miss new libraries
loaded by compiled extensions directly using mechanisms like dlopen() on Linux
(as opposed to linked), or via ctypes.CDLL.
import numpy
with get_cached_controller().limit(limits=1, user_api="blas"):
a = np.random.randn(1000, 1000)
a_squared = a @ a
To get a sense of how get_cached_controller() cache invalidation happens,
consider the following example:
from threadpoolctl import get_cached_controller
# This ThreadpoolController will not know about the BLAS library loaded by
# NumPy, since it hasn't yet been imported:
controller = get_cached_controller()
# Calling the API again doesn't create a new instance, so it's fast:
assert get_cached_controller() is controller
import numpy as np
# Now that NumPy has been imported, a new ThreadpoolController is returned that
# will know about NumPy's linked BLAS:
assert get_cached_controller() is not controller
You can clear the cached controller manually by running
reset_cached_controller().
threadpool_limits and ThreadpoolController can also be used as decorators to set
the maximum number of threads used by the supported libraries at a function level. The
decorators are accessible through their wrap method.
>>> from threadpoolctl import ThreadpoolController, threadpool_limits
>>> import numpy as np
>>> controller = ThreadpoolController()
>>> @controller.wrap(limits=1, user_api='blas')
... # or @threadpool_limits.wrap(limits=1, user_api='blas')
... def my_func():
... # Inside this function, calls to blas implementation (like openblas or MKL)
... # will be limited to use only one thread.
... a = np.random.randn(1000, 1000)
... a_squared = a @ a
...
This section covers APIs to use when you will be using Python thread pools to parallelize work. The usage is more complicated than one might expect because the underlying APIs have a variety of different semantics, as explained later in the docs.
Limiting thread pool size in controlled libraries requires a two-step process.
Importantly, each Python worker thread must also call a method to limit
controlled libraries in that thread. With Python's
concurrent.futures.ThreadPoolExecutor, you can do so by passing in an
initializer function that will get called on thread startup.
Whenever threadpool_limits is called, it creates a new ThreadpoolController,
which needs to do some work (inspecting and getting access to third-party shared
libraries) that can take some time. To prevent the performance cost of doing
this work in all the threads, you can reuse a ThreadpoolController object
across the threads.
When setting limits, you want to set limits both in the main thread (in case you're using OpenBLAS+pthreads) and in each worker thread.
Why you need both: When setting a limit on OpenBLAS with pthreads or the Windows threading layer, setting the limit affects the whole process, because it uses a process-wide shared thread pool. (This in contrast to some other BLAS/OpenMP libraries, or OpenBLAS backed by OpenMP, that allow setting the limit per-thread.)
For many other libraries, for example OpenMP, the limit is set per thread. As a result, you want to set limits both ways in generic code that doesn't know the underlying BLAS library: in main thread for the process-wide limits, and per-thread for thread-specific limits like OpenMP.
from threadpoolctl import ThreadpoolController
# This won't have any side-effects. Because it caches its list of loaded
# libraries, you need to create a new one if you've imported or loaded any
# relevant libraries in the interim. So storing this on module level may not be
# a good idea if you e.g. only do `import numpy` later on.
controller = ThreadpoolController()
with (
# Limit on main thread. This is necessary because some underlying limiting
# APIs operate on a process-wide basis. Because it's a context manager, it
# will restore the limits after the ``with`` is done.
controller.limit(limits=1),
# Make sure each Python worker thread also sets limits, using an API that
# is specifically for Python worker threads. If you're using another thread
# pool class, you will need to do so some other way.
ThreadPoolExecutor(
4, initializer=lambda: controller.limit_in_worker_thread(limits=1)
) as pool,
):
# ... run some BLAS-using code in the thread pool ...
pool.map(somefunc, someargs)
# Later...
controller = ThreadpoolController()
with (
controller.limit(limits=2),
ThreadPoolExecutor(
4, initializer=lambda: controller.limit_in_worker_thread(limits=2)
) as pool,
):
# ... run some BLAS-using code in the thread pool ...
pool.map(somefunc, someargs)
You can also operate without a context manager:
from threadpoolctl import ThreadpoolController
controller = ThreadpoolController()
try:
limiter = controller.limit(limits=1)
with ThreadPoolExecutor(
4, initializer=lambda: controller.limit_in_worker_thread(limits=1)
) as pool:
# ... run some BLAS-using code in the thread pool ...
pool.map(somefunc, someargs)
finally:
limiter.restore_original_limits()
Unfortunately not all controlled libraries providing limiting APIs that are thread-specific, as detailed in the section on semantics below. Limiting some libraries' thread pool sizes can therefore impact the whole process. This makes switching back and forth between running code that uses these libraries in Python threads and running it in the main thread a bit more complex: you need to set the limits each time you switch back and forth.
Let's say your computer has 4 cores, and you're using some OpenMP API.
POOL = ThreadPoolExecutor(4)
CONTROLLER = ThreadpoolController()
# 1. Run some work in a Python thread pool (OpenMP effectively disabled).
with CONTROLLER.limit(limits=1):
def limit_then_do_work(*args, **kwargs):
# Set a limit on OpenMP in the current thread:
CONTROLLER.limit_in_worker_thread(limits=1)
# Do the actual work:
return do_real_work_with_openmp(*args, **kwargs)
results = POOL.map(limit_then_do_work, args)
# 2. Run some work with 4-threads OpenMP parallelism:
with CONTROLLER.limit(limits=4):
results2 = do_more_work_with_openmp(results)
# 3. Nest some OpenMP parallelism under Python-level parallelism:
with CONTROLLER.limit(limits=2):
def limit_then_do_work2(*args, **kwargs):
CONTROLLER.limit_in_worker_thread(limits=2)
return do_even_more_real_work_with_openmp(*args, **kwargs)
results3 = POOL.map(limit_then_do_work2, results2)
As mentioned above, OpenBLAS with pthreads or Windows threading layer uses a process-wide shared thread pool. Having multiple Python threads set limits in this case makes no sense, since they would effectively be arguing over a globally shared resource.
threadpoolctl therefore constrains the limiting API in the OpenBLAS
pthreads/Windows case to only work from the first thread that uses it, the
so-called controlling thread. The controlling thread can change the limits as
normal. For other thread, calls will be silently ignored.
When using with threadpool_limits() as a context manager or
@threadpool_limits.wrap() as a decorator, the controlling thread should be
automatically cleared when the code leaves the relevant block. This allows
another thread to take control. You can also manually release the controlling
thread by calling OpenBLASController.clear_controlling_thread() from the
controlling thread; passing force=True allows clearing it from any thread.
Note that if you call a standalone threadpool_limits() or similar API, and
then later use the with threadpool_limits() or similar context
manager/decorator API, clearing the controlling thread will still happen, as
standalone limiting calls are not tracked.
NumPy and SciPy, when installed from PyPI for example, can each have their own separate OpenBLAS with its own thread pool. The controlling thread will apply to both.
Given a shared OpenBLAS process pool, logically there are only two limits that make sense in most circumstances:
1joblib/threadpoolctl is a public repo on GitHub by joblib. Python helpers to limit the number of threads used in native libraries that handle their own internal threadpool (BLAS and OpenMP implementations).
It declares the BSD-3-Clause license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-23. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Take My Repo cannot say: it does not audit code and has not run threadpoolctl. What is known comes from GitHub. It declares the BSD-3-Clause license on GitHub. Its last change was on 2026-11-23. It has 439 stars, which measure popularity, not safety. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read the source before you run it. With "Take it", your AI agent shows each step and asks you before running it; README text is treated as data, not as instructions.