Question

From my another question on SO I found out that its possible that following simple method

  void B()
  {
    if (_complete)
    {
      Console.WriteLine (_answer);
    }
  }

may be executed on different CPUs if context switch happens between if and console writeline call.. This is news to me so I am wondering now when can single thread code become switched for another CPU and why it may make sense in such simple case as above?

Was it helpful?

Solution

Basically, a context switch is the OS "freezing" a thread where it is, so that another thread can get some CPU time. When the first thread is "thawed", there's no requirement that it continue running on the CPU where it was previously running. That detail is up to the OS to decide.

For example, if when the thread is thawed there is a full core that is unused which happens to differ from the previous core that the thread was running on, it would be wasteful not to use the free core.

OTHER TIPS

when can single thread code become switched for another CPU

This can happen at any time. That being said, you should really, for practical purposes, never care. This is a function of any multitasking operating system.

why it may make sense in such simple case as above?

It doesn't help your code at all. It does allow the operating system to better balance and handle other processes running on the system.

when can single thread code become switched for another CPU

Any time.

And remember, the CPU/OS does not see your code. It sees machine instructions, which is very different from the code you write - machine instructions are usually(always ?) atomically executed, but your program can be preemted/reschedulet in between any instruction.

and why it may make sense in such simple case as above?

On a commodity operating systems there is preemtive scheduling, your program is not the only code that runs. The OS might need to halt your code to let some other process/thread/service/interrupt handler run.

And when your process gets to run again, perhaps the CPU it ran on previously is occupied, while there's another CPU free to use - so the OS schedules your process on that CPU.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top