python / python/cpython

os.process_cpu_count() should take cgroups CPU limitations into account (on Linux)

Đang mở
#149,452 10 bình luận 2 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

extension-modules topic-multiprocessing type-feature
Ngôn ngữ chính
Python
Star
77.2k
Fork
35.9k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

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.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu từ entry point os.process_cpu_count() của Python và tái hiện ví dụ Docker --cpus=2 trên Linux. Đọc implementation của loky.cpu_count() được liên kết và issue CPython 77167 trước đó để biết bối cảnh. Được xem là hoàn tất khi process_cpu_count() tính đến các giới hạn CPU của cgroup trên Linux và trả về số lượng bị giới hạn trong trường hợp container.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
docker, kubernetes, linux, python
Lĩnh vực
devops, operating-systems
Loại issue
Tính năng
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Ít trao đổi
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
52/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.