How can I set the processor affinity of a process on Linux?


4 Answers 4


I have used taskset for this. If you have taskset installed, something like:

taskset -cp 0,2 45678

would set the process with id 45678 to have an affinity to cpus 1 and 3.

  • 1
    I'm getting: taskset: failed to execute -p: No such file or directory.
    – Calmarius
    Commented Apr 7, 2020 at 7:02
  • maybe taskset changed it's params since I originally posted this?
    – kbyrd
    Commented Apr 7, 2020 at 14:57
  • Syntax seems to be taskset -pc 0,2 45678
    – Cameron
    Commented Sep 28, 2020 at 12:54
  • fixed, thanks. Actually tested on a cmdline. As of now. -cp is correct
    – kbyrd
    Commented Sep 28, 2020 at 15:11
  • 2
    Usage in the form taskset -pc cpulist pid e. g. taskset -pc 0,3,7-11 700 is actually included in compiled-in help (tested on taskset from util-linux 2.32.1 and 2.29.2). Both -cp and -pc work for me.
    – d.c.
    Commented Feb 5, 2021 at 14:04

Inside the process, the call would be sched_setaffinity(), or for pthreads stuff, pthread_setaffinity_np()

On a related note, if you're worrying about CPU affinity of your program, it may be worthwhile to pay attention to how it's doing memory allocation as well. Larger systems with memory attached to more than one controller (i.e. multiple CPU sockets, each with their own) will have variable latency and bandwidth between different CPU-memory pairs. You'll want to look into NUMA affinity as well, using the numactl command or the system calls that it works with. One program I worked on got a 10% performance improvement from this.


You need to install schedutils (Linux scheduler utilities). I have use it on my Ubuntu Desktop.

SF link

taskset -c 1-3 ./a.out arg1 arg2

launches the a.out process with given arguments and affinity set to processors 1, 2 or 3 (zero based).

Here is a minimal C test program that can be used to see it in action: https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .