os.process_cpu_count() should take cgroups CPU limitations into account (on Linux)
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Feature or enhancement
Proposal:
os.process_cpu_count() currently takes CPU core scheduler affinity into account. However, there are other ways to restrict CPU usage on Linux, most significantly cgroups as used by Docker and Kubernetes.
For example, if I ask for 2 cpus for a container, process_cpu_count() does not respect that:
$ docker run -it --cpus=2 python:3.14-slim python -c "import os; print(os.process_cpu_count())"
20
This can lead to surprising behavior for users, where too many threads are started in a container given the available resources.
An existing implementation in Python
In contrast, the loky.cpu_count() function does know about these restrictions:
$ docker run -it --cpus=2 python:3.14-slim bash
root@557b43351822:/# pip install --quiet loky
root@557b43351822:/# python
Python 3.14.2 (main, Jan 13 2026, 03:08:39) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import loky
>>> loky.cpu_count()
2
You can read the loky implementation (permanlink to version as of May 6, 2026).
Has this already been discussed elsewhere?
This is a minor feature, which does not need previous discussion elsewhere
Links to previous discussion of this feature:
There was some discussion in https://github.com/python/cpython/issues/77167. Given cpu_count() is now distinct from process_cpu_count(), it seems useful to make the latter accurate, and cgroups as the basis for Linux containerization has a massive scale of deployment.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at Python's os.process_cpu_count() entry point and reproduce the Docker --cpus=2 example on Linux. Read the linked loky.cpu_count() implementation and the earlier CPython issue 77167 for context. Done means process_cpu_count() accounts for Linux cgroup CPU limits and returns the constrained count in the container scenario.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- docker, kubernetes, linux, python
- Domain
- devops, operating-systems
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 52/100