[patch v3] manual: add remaining CPU_* macros
Collin Funk
collin.funk1@gmail.com
Thu May 15 02:10:06 GMT 2025
DJ Delorie <dj@redhat.com> writes:
> +Here's an example of how to use most of the above to limit the number
> +of CPUs a process runs on, not including error handling or good logic
> +on CPU choices:
> +
> +@example
> +#define _GNU_SOURCE
> +#include <sched.h>
> +#include <sys/sysinfo.h>
> +#include <unistd.h>
> +void limit_cpus (void)
> +@{
> + unsigned int mycpu;
> + size_t nproc, cssz, cpu;
> + cpu_set_t *cs;
> + getcpu (&mycpu, NULL);
> + nproc = get_nprocs_conf ();
> + cssz = CPU_ALLOC_SIZE (nproc);
> + cs = CPU_ALLOC (nproc);
> + sched_getaffinity (0, cssz, cs);
> + if (CPU_COUNT_S (cssz, cs) > nproc / 2)
> + @{
> + for (cpu = nproc / 2; cpu < nproc; cpu ++)
> + if (cpu != mycpu)
> + CPU_CLR_S (cpu, cssz, cs);
> + sched_setaffinity (0, cssz, cs);
> + @}
> + CPU_FREE (cs);
> +@}
> +@end example
Thanks to Mark for pointing out the issues in the original example. I
learned my lesson and compiled it this time and checked the affinity
before and after. It worked as expected and halved the affinity.
One minor request, though. Can we change:
void limit_cpus (void)
to:
void
limit_cpus (void)
It is more consistent with the rest of the examples in the manual.
Otherwise, the patch is good to me.
Reviewed-by: Collin Funk <collin.funk1@gmail.com>
Collin
More information about the Libc-alpha
mailing list