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

10,388

CPU's don't do context switching. Operating Systems do.

In essence, an OS executes a context switch by loading a new context (registers, memory mappings, etc) in a CPU core. Threads are an OS structure in which such contexts can be saved. Hence, the OS is also responsible for picking a nonrunning thread to load the CPU context from.

If the OS were to pick a running thread, two cores would try to run the same thread. That's bound to cause confusion as they'd share the same memory, and that single thread won't expect to be run in parallel with itself (!) So no OS would do such a thing.

Share:
10,388
gablin
Author by

gablin

Meh.

Updated on June 13, 2022

Comments

  • gablin
    gablin about 2 years

    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?

  • gablin
    gablin over 13 years
    I never said that the CPU does the context switching. I said that the code responsible (i.e. the OS) for doing the context switch is executed on a CPU. But how's that handled when we have more than one CPU? Is the context switching code executed on all CPUs?