Skip to content

Instantly share code, notes, and snippets.

@plusk01
Last active February 14, 2023 20:43
Show Gist options
  • Save plusk01/f7a540efa3b958ed2b9e301549fe25b6 to your computer and use it in GitHub Desktop.
Save plusk01/f7a540efa3b958ed2b9e301549fe25b6 to your computer and use it in GitHub Desktop.
Understanding CPU affinity with taskset

CPU Affinity

In a single core system, the OS allows multiple processes to run by sharing CPU time with the multiple processes. This is called concurrency, which gives the illusion of multiple processes executing at once, but is in fact just using a scheduler to give each process dedicated time on the CPU. The time associated with switching processes on a single core is overhead caused by context switching.

When a multi-core processor is available to an OS (e.g., Linux), the scheduler will do its best to allow processes to run simultaneously (by placing processes on different cores) in addition to running concurrently (different processes on the same core).

To control which core a process runs on, we can tell the scheduler to give a process a certain affinity towards a given set of CPUs.

Using taskset, we can get/set the CPU affinity of a particular process. Consider the following example.

  1. In one terminal, open htop.

  2. In another terminal, run while true; do true; done; This will create an infinite loop that burns CPU (without printing).

    • You should notice one of the cores in htop becomes slammed.
  3. Get the PID of the bash terminal that is running the infinite while loop: ps aux | grep bash (hint: the one that has the TIME column increasing -- this is the amount of CPU time that this process has taken up).

  4. Move the process to another CPU!

    • taskset -p 0x01 <pid> moves to CPU #1
    • taskset -p 0x08 <pid> moves to CPU #4

Open Questions and References

  1. Threading vs Processes vs Forking (in Linux)
    • SO question
    • What is the most scalable / general to other OSes?
  2. SO: How to control which core a process runs on
  3. C++11 Threads and Affinity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment