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?
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.