multithreadingmulticorecontext-switching

How is context switching of threads done on a multi-core processor?


When doing context switching on a single-core processor, the code responsible is executed on the only CPU which takes care of switching the threads.

But how is this done when we have multiple CPUs? Is there a master CPU which does all the context switching of all slave CPUs? Is each CPU responsible for its own context switching? If so, how is the switching synchronized so that two CPUs are not executing the same thread? Or is there some other mechanism in place?


Solution

  • The kernel is multi-threaded. It can execute on any core. When a core comes to need to swap threads, it invokes the part of the kernel responsible for selecting the next thread it should execute.

    The kernel is multi-threaded; which is to say, it is written to be safe executing concurrently on multiple cores. As such, only one CPU ends up running any given thread, because the code is constructed such that if multiple CPUs reschedule concurrently, the correct outcome occurs.