Re: Use sched_getaffinity instead of /proc parsing for _SC_NPROCESSORS_ONLN

Bela Lubkin <[email protected]> Mon, 6 Dec 2010 13:49:01 -0800
Newsgroups gmane.linux.lib.dietlibc
Message-ID <[email protected]>
Indan Zupancic wrote:

> +/*
> + * Only meaningful for sysconf_cpus so far.
> + * If set, you can unset SLASH_PROC_OK for sysconf(_SC_NPROCESSORS_ONLN).
> + */
> +#define _HAVE_LINUX26
> +
...
> @@ -63,8 +69,16 @@ long sysconf(int name)
>      return NGROUPS_MAX;
> 
>    case _SC_NPROCESSORS_ONLN:
> +#ifndef _HAVE_LINUX26
>      return __sc_nr_cpus();
> -
> +#else
> +    {
> +    cpu_set_t m;
> +    if (sched_getaffinity(0, sizeof(m), &m))
> +        return 1;
> +    return CPU_COUNT(&m);
> +    }
> +#endif

Deciding these things based on OS name & version is so '90s.  Instead of
adding an OS define that only controls one feature, it should key off of
a feature define: USE_GETAFFINITY_CPU_COUNT or something like that.
Except...

The setting of *that* could be controlled by a "_HAVE_LINUX26"; but what
are you really testing?  Red Hat adds the affinity calls to their 2.4
kernels (RHEL3); other distros probably also did.

It seems to me: (1) it is desirable to have working get/setaffinity() on
any kernel that supports them; (2) it is desirable to have stubs [ignore
set(), return 1 from get()] on kernels that don't support them; (3) if
getaffinity always exists, there is no reason to #ifdef this code at
all.  Except conservatism, and the possibility that some kernel / arch
might have a better way.

For conservatism, `#ifdef USE_CLUMSY_OLD_PROC_SC_NPROCESSORS_ONLN' the
old code :).  For other arches, well -- if there's a better way someone
can add code for it, including the necessary #ifdef's...

Other than that, the patchset (as revised) looks reasonable after a
lightweight review.

>Bela<