Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

c# - SwitchToThread vs Sleep(1)

I'm wondering what's the actual difference between calling Thread.Sleep(1) and calling SwitchToThread (if we ignore that it's currently not exposed by the BCL).

Joe Duffy mentions in his post that:

"The kernel32!SwitchToThread API doesn't exhibit the problems that Sleep(0) and Sleep(1) do." (regarding the scheduler's behavior)

Why won't Sleep behave exactly like SwitchToThread? Why this differentiation exist, and for what is it good for? (if at all..)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two differences. The first is mentioned in the MSDN docs for SwitchToThread:

The yield of execution is limited to the processor of the calling thread. The operating system will not switch execution to another processor, even if that processor is idle or is running a thread of lower priority.

Sleep(0) will allow threads on other processors to run, as well.

SwitchToThread only yields to a single thread scheduling context, as well. Sleep, on the other hand, has multiple conditions for which it waits. The docs for SleepEx spell this out in detail:

* An I/O completion callback function is called
* An asynchronous procedure call (APC) is queued to the thread.
* The time-out interval elapses

This will yield to multiple threads.

In general, Sleep(0) will be much more likely to yield a timeslice, and will ALWAYS yield to the OS, even if there are no other threads waiting. This is why adding a Sleep(0) in a loop will take the processor usage from 100% (per core) to near 0% in many cases. SwitchToThread will not, unless another thread is waiting for a time slice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...