Skip to content

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

@itamarst

Description

@itamarst

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 #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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions