1.3.1. Processor Affinity or CPU Pinning
Each time a job or a thread is preempted and another job or thread is scheduled, the operating system might assign a new job or thread to a core that is free. Due to this reason, the core to which a given thread or process is assigned to can be different each time. Each time a thread is assigned to a core, the processor must copy a thread's relevant data and instructions into its cache, if the data is not already in the cache. This means that the cache must be updated each time a thread is rescheduled on a new core.
Processor affinity or CPU pinning enables applications to bind or unbind a process or a thread to a specific core or to a range of cores or CPUs. The operating system ensures that a given thread executes only on the assigned core(s) or CPU(s) each time it is scheduled, if it was pinned to a core.
Processor affinity takes advantage of the fact that the remnants of a process execution remains valid when the same process or thread is scheduled a second time on the same processor. So, the cache may still be valid when a thread execution is re-scheduled after being preempted. This helps scale the performance on multiple core processor architectures that share the same global memory and have local caches (UMA Architecture).
Operating systems support CPU affinity through APIs. The *NX platform has a scheduler library that provides APIs for CPU affinity. The following code snippet when called within a thread sets its affinity to cpu_id:
CPU_SET (cpu_id, &cpu_set);
sched_setaffinity (0, sizeof(cpu_set_t), &cpu_set);