Previous: Memory Resources, Up: Resource Usage And Limitation


22.5 Learn about the processors available

The use of threads or processes with shared memory allows an application to take advantage of all the processing power a system can provide. If the task can be parallelized the optimal way to write an application is to have at any time as many processes running as there are processors. To determine the number of processors available to the system one can run

       sysconf (_SC_NPROCESSORS_CONF)

which returns the number of processors the operating system configured. But it might be possible for the operating system to disable individual processors and so the call

       sysconf (_SC_NPROCESSORS_ONLN)

returns the number of processors which are currently online (i.e., available).

For these two pieces of information the GNU C Library also provides functions to get the information directly. The functions are declared in sys/sysinfo.h.

— Function: int get_nprocs_conf (void)

Preliminary: | MT-Safe | AS-Unsafe heap lock | AC-Unsafe lock fd mem | See POSIX Safety Concepts.

The get_nprocs_conf function returns the number of processors the operating system configured.

This function is a GNU extension.

— Function: int get_nprocs (void)

Preliminary: | MT-Safe | AS-Safe | AC-Safe fd | See POSIX Safety Concepts.

The get_nprocs function returns the number of available processors.

This function is a GNU extension.

Before starting more threads it should be checked whether the processors are not already overused. Unix systems calculate something called the load average. This is a number indicating how many processes were running. This number is average over different periods of times (normally 1, 5, and 15 minutes).

— Function: int getloadavg (double loadavg[], int nelem)

Preliminary: | MT-Safe | AS-Safe | AC-Safe fd | See POSIX Safety Concepts.

This function gets the 1, 5 and 15 minute load averages of the system. The values are placed in loadavg. getloadavg will place at most nelem elements into the array but never more than three elements. The return value is the number of elements written to loadavg, or -1 on error.

This function is declared in stdlib.h.