Pages

May 15, 2011

CPU Affinity


When you are using SMP (Symmetric MultiProcessing) you might want to override the kernel's process scheduling and bind a certain process to a specific CPU(s).

#define _GNU_SOURCE
#include 
long
sched_setaffinity(pid_t pid, unsigned int len,unsigned long *user_mask_ptr);
long
sched_getaffinity(pid_t pid, unsigned int len,unsigned long *user_mask_ptr);
The first system call is used to set the affinity of a process, and the second system call retrieves it.
In either system call, the PID argument is the PID of the process whose mask you wish to set or retrieve. If the PID is set to zero, the PID of the current task is used.
Mask
Bit 0 -> CPU 1, Bit 1 -> CPU 2, Bit 2 -> CPU 3, Bit 3 -> CPU 4  Eg.,0xFFFFFFFF=>All CPUs are available


Eg.,
   pid_t pid;
    unsigned long mask;
    int rc;


    pid = getpid();
    rc = sched_getaffinity(0, sizeof(mask), &mask);
    if (rc == -1) {
        printf("sched_getaffinity() error !!! (%d)\n", errno);
    }
    else {
        printf("mask : 0x%08x\n", mask);
    }


    mask = 0x2;
    rc = sched_setaffinity(0, sizeof(mask), &mask);
    if (rc == -1) {
        printf("sched_setaffinity() error !!! (%d)\n", errno);
    }
    else {
        printf("mask : 0x%08x\n", mask);
    }


    mask = 0x0;
    rc = sched_getaffinity(0, sizeof(mask), &mask);
    if (rc == -1) {
        printf("sched_getaffinity() error !!! (%d)\n", errno);
    }
    else {
        printf("mask : 0x%08x\n", mask);
    }
Further Reading
http://www.linuxjournal.com/article/6799?page=0,0

No comments: