Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a thread on a new core?

Is there a way to tell the OS to run a process/thread on a separate core? To keep that process isolated?

Like using pthreads or fork() in C?

Is there a different way to do it in Linux vs Windows?

like image 900
SKrish Avatar asked Dec 03 '25 04:12

SKrish


1 Answers

If you want to ensure that the processes/threads run on a separate CPU core, then

  • on Microsoft Windows, you can use the functions SetProcessAffinityMask and SetThreadAffinityMask, and
  • on Linux, you can use the the function sched_setaffinity if not using pthreads, and if using pthreads, you should use pthread_setaffinity_np instead.

The function fork is not useful for this, as the purpose of this function is to split one process into two different processes, which is something completely different. The function fork will make no attempt to ensure that these two processes will run on separate cores. Which core which process runs on is entirely up to the scheduler of the kernel, unless you set an affinity mask as described above.

In your question, your stated goal is to keep the processes "isolated". It is worth noting that even two processes running on the same core will be isolated from each other, because their virtual address spaces will be separate. Whenever a CPU core switches to running a different process, the two virtual address spaces will be swapped as part of the context switch. Therefore, two processes running on the same core will only interfere with each other with regards to performance.

like image 161
Andreas Wenzel Avatar answered Dec 05 '25 22:12

Andreas Wenzel