os.process_cpu_count() should take cgroups CPU limitations into account (on Linux)
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
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.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Python 的 os.process_cpu_count() 入口开始,在 Linux 上复现 Docker --cpus=2 示例。阅读链接的 loky.cpu_count() 实现以及之前的 CPython issue 77167,以了解背景。完成的标准是 process_cpu_count() 考虑 Linux cgroup 的 CPU 限制,并在容器场景中返回受限的数量。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- docker, kubernetes, linux, python
- 领域
- devops, operating-systems
- Issue 类型
- 功能
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 冷清
- 描述清晰度
- 基本清楚
- 新手友好度
- 52/100