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.
-
In one terminal, open
htop
. -
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.
- You should notice one of the cores in
-
Get the PID of the bash terminal that is running the infinite while loop:
ps aux | grep bash
(hint: the one that has theTIME
column increasing -- this is the amount of CPU time that this process has taken up). -
Move the process to another CPU!
taskset -p 0x01 <pid>
moves to CPU #1taskset -p 0x08 <pid>
moves to CPU #4
- Threading vs Processes vs Forking (in Linux)
- SO question
- What is the most scalable / general to other OSes?
- SO: How to control which core a process runs on
- C++11 Threads and Affinity