Skip to content

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

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.

Linked PRs

Activity

  1. added
    type-feature
    on May 6, 2026
  2. added
    extension-modules
    on May 6, 2026
  3. picnixz commented on May 6, 2026

    @picnixz
    Member

    This looks like a nontrivial implementation. Should we really make it part of the stdlib as this may vary across platforms and we would need to maintain this? Iam tagging it as a mp issue event though it is not mp-really (but it is related to mt/mp)

  4. itamarst commented on May 6, 2026

    @itamarst
    Author

    If the final decision is that it's not worth doing, the minimalist option is to document the limitations of process_cpu_count() and point readers at better alternatives.

    As a reference point, the (fairly minimal) Rust standard library decided to add cgroups support in 1.61 to the equivalent API. The detailed changelog explained that "Since available_parallelism is often used to create a thread pool for parallel computation, which may be CPU-bound for performance, available_parallelism will return a value consistent with the ability to use that many threads continuously, if possible. For instance, in a container with 8 virtual CPUs but quotas only allowing for 50% usage, available_parallelism will return 4."

    I guess if Rust ever becomes a CPython dependency that would allow for an easy fix...

  5. picnixz commented on May 6, 2026

    @picnixz
    Member

    I am perfectly ok for a doc update for now as it is largerly non-controversial. I would be interested in having something in the stdlib though, but the question is:

    • can all Tier 1 platforms be properly supported?
    • can Tier 2/3 platforms be supported at minimal cost?
    • how maintainable will it be?

    UUID is another beast where there are lots of checks since we want to support many platforms and I would honestly want to avoid this kind of code if possible.. if every Linux distribution needs its own check it will be hard to maintain properly =/ but we can make it as an iterative approach (start with common checks). We however do not want to end up with frozen dev as for ctypes.util.find_library() (I think we soft-deprecated that function)

  6. itamarst commented on May 7, 2026

    @itamarst
    Author

    At first glance at the Rust std implementation as a potential baseline, I think it's mostly just adding cgroups support for Linux, none of the other OSes have much custom code beyond what Python already does (https://github.com/rust-lang/rust/tree/main/library/std/src/sys/thread).

  7. encukou commented on May 7, 2026

    @encukou
    Member

    Turns out this is a duplicate of #77167 & #80235.

    I'm not sure I fully agree with the decisions there, but, it does look like an “available_parallelism” API serves a slightly different purpose than process_cpu_count -- though arguably a more niche one: AFAIK @vstinner added process_cpu_count in the context of CPU isolation, for reliable beachmark timing.

    Given that multiprocessing pools need a default, perhaps “available_parallelism” logic should live somewhre in stdlib.


    I guess if Rust ever becomes a CPython dependency that would allow for an easy fix...

    Or just shell out to nproc if that's available, right? That has cgroups v2 support, in the latest versions.


    can all Tier 1 platforms be properly supported?
    can Tier 2/3 platforms be supported at minimal cost?
    how maintainable will it be?

    Those are questions for a different feature request, though one that's implied here: “Make os.process_cpu_count() reliably take platform CPU quota into account.” That is an unreachable state.
    It would turn os.process_cpu_count is a pit of unbounded complexity, similar to shutil.copyfile/os.sendfile implementing 3+ different “best” ways to move bytes around on specific systems.
    But alas, in this case, the stdlib os module is probably the right layer for this complexity. We already started on this path with the affinity support.

    On its own, the cgroups feature will not vary across platforms -- it's platform-specific. And it should be rather stable once implemented. Other platforms, and Linux, might add other limiting mechanisms; that's where maintainability cost is. But IMO we should take patches for those on all “major” platforms (even unsupported ones, under the PEP 11 policy).

  8. picnixz commented on May 7, 2026

    @picnixz
    Member

    Those are questions for a different feature request, though one that's implied here: “Make os.process_cpu_count() reliably take platform CPU quota into account.” That is an unreachable state.

    Actually that was my question but I phrased it poorly :) Now, as I said, I'm ok with this addition, just that we should be careful with how precise we'll be. Relying on cgroup only first should be ok since it's kinda standardized and we'll see in the future about other limiting mechanisms.

    I should however apologize concerning the loky statement: the complexity mainly comes from the physical core counting. If we are only interested in logical available cores, the features looks not that complex to do.

  9. encukou commented on May 7, 2026

    @encukou
    Member

    This goes directly against an earlier decision; we need to address @vstinner's point:

    I mean that in general, Linux cgroups CPU limits are not directly related to a whole number of CPU and so it's hard to use such limit to update os.cpu_count() or os.process_cpu_count().

    IMO, rounding up is the correct thing to do. If your quota is “2.5 CPUs”, 2 threads will not saturate that and 4+ is definitely wasteful (if they're CPU-bound).
    It's also what nproc does (at least the version in Fedora currently):

    $ podman run --rm -it --cpus=2 fedora 
    [root@a3f691dab876 /]# nproc
    2
    [root@a3f691dab876 /]# cat /sys/fs/cgroup/cpu.max
    200000 100000
    [root@a3f691dab876 /]# exit
    
    $ podman run --rm -it --cpus=2.5 fedora 
    [root@cf0da4e95957 /]# nproc
    3
    [root@cf0da4e95957 /]# cat /sys/fs/cgroup/cpu.max
    250000 100000
    
  10. vstinner commented on May 7, 2026

    @vstinner
    Member

    Copy of my comment (2023).

    pylint parses different cgroup files:

    • /sys/fs/cgroup/cpu/cpu.cfs_quota_us
    • /sys/fs/cgroup/cpu/cpu.cfs_period_us
    • /sys/fs/cgroup/cpu/cpu.shares

    Code: https://github.com/d1gl3/pylint/blob/2625c341e07f60276dcd2c23a8b47f49f80688a0/pylint/lint/run.py#L34-L80


    On a recent container (ex: Fedora 44), none of these files exist, but I have /sys/fs/cgroup/cpu.max (cgroup version 2).

    coreutils nproc program calls num_processors() function which is implemented in gnulib:lib/nproc.c. This function gets the CPU quota:

    • Get the current cgroup from /proc/self/cgroup
    • Get the current mount point from /proc/mounts
    • Iterate on <cgroup2 mount point> / <cgroup> / "cpu.max" (ignore line starting with "max"), remove the last part of cgroup at each iteration
    • Return the minimum CPU count

    The CPU quota is not used if the process scheduler is SCHED_FIFO, SCHED_RR or SCHED_DEADLINE.

    I reimplemented the code in Python:

    import os
    
    def unescape_mount(text):
        text = text.replace(r"\040", " ")
        text = text.replace(r"\011", "\t")
        text = text.replace(r"\012", "\n")
        text = text.replace(r"\134", "\\")
        return text
    
    def cgroup2_get_mount_point():
        if os.path.exists("/sys/fs/cgroup/cgroup.controllers"):
            return "/sys/fs/cgroup"
    
        try:
            fp = open("/proc/mounts")
        except OSError:
            return
        with fp:
            for line in fp:
                parts = line.split()
                mnt_fstype, mnt_dir, mnt_type, *_ = parts
                if mnt_type == "cgroup2":
                    return unescape_mount(mnt_dir)
    
    def cgroup_get_ncpus(filename):
        try:
            fp = open(filename)
        except OSError:
            return
        with fp:
            line = fp.readline()
    
        if line.startswith("max"):
            return
    
        parts = line.split()
        if len(parts) != 2:
            return
    
        try:
            quota = int(parts[0])
            period = int(parts[1])
        except ValueError:
            return
    
        # rounds up (towards +infinity)
        ncpus = (quota + (period - 1)) // period
        return max(ncpus, 1)
    
    def cgroup_cpu_quota():
        cgroup = None
        try:
            fp = open("/proc/self/cgroup")
        except OSError:
            return
        with fp:
            for line in fp:
                if line.startswith("0::/"):
                    cgroup = line[3:].rstrip("\n")
    
        mount = cgroup2_get_mount_point()
        if not mount:
            cgroup = None
    
        if not cgroup:
            return None
    
        cpu_quota = None
        while cgroup:
            cpu_max_filename = os.path.join(mount, cgroup[1:], "cpu.max")
            ncpus = cgroup_get_ncpus(cpu_max_filename)
            if ncpus is not None:
                if cpu_quota is None or ncpus < cpu_quota:
                    cpu_quota = ncpus
                if cpu_quota == 1:
                    # cpu_count() will return 1 minimum, so no point going lower
                    return 1
    
            parts = cgroup.rpartition('/')
            if not parts[1]:
                break
            cgroup = parts[0]
    
        return cpu_quota
    
    def cpu_count():
        sched = os.sched_getscheduler(0)
        if sched in (os.SCHED_FIFO, os.SCHED_RR, os.SCHED_DEADLINE):
            return
        cpu_quota = cgroup_cpu_quota()
        if cpu_quota is not None:
            return cpu_quota
        return os.cpu_count()
    
    print(cpu_count())
  11. vstinner commented on May 7, 2026

    @vstinner
    Member

    cgroup v2 has other files related to the CPU:

    • cpu.weight
    • cpuset.cpus.effective
    • cpuset.cpus.isolated
    • cpuset.mems.effective

    These files are not used by gnulib num_processors() function. Should we parse these files as well?

  12. encukou commented on May 8, 2026

    @encukou
    Member

    AFAIK cgroups v1 (that is, what pylint is using) is kinda obsolete already; perhaps we can do just v2 if we're adding this to 3.16?

    IMO iterating the mounts is hypercorrect, a holdover from v1 maybe. /sys/fs/cgroup should work fine. (For example, we also open /dev/urandom even though a sysadmin could theoretically put that device elsewhere.)

    cpu.weight

    This is relative weight (like nice). For “available_parallelism” we should ignore it; we don't know what the system load will be when worker threads are running.

    cpuset

    sched_getaffinity reflects this already:

    $ sudo podman run --rm -it --cpuset-cpus=1,2 fedora
    [root@eb836fb5bdcb /]# cat /sys/fs/cgroup/cpuset.cpus.effective 
    1-2
    [root@eb836fb5bdcb /]# python3
    >>> import os
    >>> os.process_cpu_count() 
    2
    >>> os.cpu_count()
    20
    
  13. itamarst commented on Nov 23, 2026

    @itamarst
    Author

    I'm going to try to turn @vstinner's sketch into a real PR.

  14. moved this from Todo to In Progress in OS issues 💻on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulestopic-multiprocessingtype-feature

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions