How to Set Processor Affinity for a Specific Task

Linux operating systems work very well with multi-processor servers. Today’s dedicated servers almost always have multiple processors or cores. When you have 4, 8, or even more logical CPUs, you can use Linux’s scheduling system to assign specific tasks to individual CPUs. As long as the task is assigned to that particular CPU, it will not stray and attempt to access power from the others. This process is called CPU affinity.

To use CPU affinity, you should install a package called schedutils, which contains the actual command you need: taskset. To install schedutils on Red Hat Enterprise Linux or CentOS, type the following as root:

yum install schedutils

The latest versions of Debian and other Debian-based systems (such as Ubuntu) have schedutils installed by default under the util-linux package.

Taskset uses a bitmask formula to identify processors. To view a list of your processors and relevant information, type:

cat /proc/cpuinfo

Assuming you have 4 processors, the mask for the first processor (#0) would look like this:


Let’s suppose you have a script running on the process PID 24328; you can assign that task to the first processor with this command:

taskset 0x00000001 -p 24328

If the bitmask thing is too confusing, taskset also has the “-c” option which allows you to use processor numbers instead:

taskset -c 3 -p 87263

For more information about taskset, type “man taskset” from the command line, or view the manual page online.