python / python/cpython

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

オープン
#149,452 コメント 10 件 リアクション 2 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

extension-modules topic-multiprocessing type-feature
主要言語
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.

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. 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

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。