开发者

Context-switch and thread execution on different CPU cores

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 di开发者_如何学Cfferent 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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜