Setting Processor Affinity on Linux

I needed to check if setting processor affinity would be able to minimize mutual performance impact of server programs running inside a Linux VM. Setting processor affinity in Linux with taskset looks pretty straightforward:

taskset -c -p <cpu#> <pid>

However, when I ran a test, I noticed that the program still use all CPUs.
So I started investigation (truly speaking, suspecting that it may be a virtualization effect) – but I was pointed out that to set processor affinity for a multithreaded application (such as the one I worked with) I need to set affinity for all tasks in /proc/<pid>/task with something like:

for p in `ls /proc/<pid>/task`; do taskset -p -c <cpu#> $p; done

as far as “threads are essentially just processes with a shared address space on Linux”.

As soon as I ran the code above for the pid, the process was limited to one processor and affinity worked fine.

So the problem was that I set affinity only for the parent process, but not for the tasks in /proc/<pid>/task (child processes inherit affinity when they are started – but in this case they all were started before I set affinity for the main process).

The process may be started with affinity from the beginning. The following, for example, works fine too:
taskset -c <cpu#> <start_command>

But if you need to set affinity for already running processes, don’t forget to set it for all tasks in /proc/<pid>/task too.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *