libsdl-org / SDL

Simple Directmedia Layer
https://libsdl.org
zlib License
9.85k stars 1.83k forks source link

SDL_GetCPUCount on Linux does not take CPU affinity into account #8135

Open Arnavion opened 1 year ago

Arnavion commented 1 year ago

SDL_GetCPUCount on Linux is implemented using sysconf(_SC_NPROCESSORS_ONLN). If a process is limited to a subset of CPUs using taskset or the cpuset cgroup controller, that will continue to return the full number of CPUs even though the process will run on only a subset of them.

I think the caller of SDL_GetCPUCount would expect to receive the number of CPUs they're allowed to use rather than the abstract number of CPUs that exist in the system. So I think it would be better if it returned the number of CPUs available to the process instead. My specific case is that use an application which uses SDL_GetCPUCount to decide how many background threads it should spawn, so it overestimates that number if I limit the process with taskset / cgroup limits.

For Linux, this means using sched_getaffinity to get the process's affinity mask, then using CPU_COUNT to get the number of available CPUs in the mask.


AFAICT this is also a problem for Windows and MacOS, since the APIs SDL_GetCPUCount uses for them are also "global" rather than scoped to the process's CPU affinity. For Windows the affinity approach is to use GetProcessAffinityMask, eg this is what dotnet does. I don't know about MacOS.

slouken commented 3 weeks ago

We are scoping work for the SDL 3.2.0 release, so please let us know if this is a showstopper for you.