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
485 views
in Technique[技术] by (71.8m points)

.net - What's the purpose of Thread.SpinWait method?

From the MSDN is not really clear its purpose.

Can it be used to simulate an intensive CPU calculation test?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

no. Its used as a replacement for very short-term sleep calls.

When you do multi-threaded locking, if the resource you're attempting to acquire is already locked, you typically go to sleep and wait for it to become free. When you do this, you give up the rest of the time that you were allocated by the scheduler to use the processor so someone else can have a go. Normally this is fine, especially for long waits, like waiting for IO, loads of other processes can run on the CPU while you're waiting for the disk spindle to rotate.

However, sometimes, you're waiting for a tiny amount of time. In these cases, you would normally give up your remaining time anyway and wait for all the other threads to do their thing before getting another go.. so you can cheat, instead of waiting, you sit there continually polling in a 'are we nearly there yet?' way. If the lock is only held for a fraction of your remaining time, this becomes a very effective means of waiting, its also very efficient as the scheduler doesn't have to get involved in rearranging all the other threads to use the time you give up if you waited normally.

Obviously, if you spin every time you want a lock, you're not going to be very popular, your app will become sluggish and use 100% CPU, but in very small doses, at the right time, it makes the app more responsive.

If you're now thinking 'when should I use it?', that's a tricky call to make - if you have a resource that is very often locked and unlocked very quickly, then a spinlock around that instead of a wait is a good idea (and then test your app for performance), if you try spinning for a short time, and then fall back to a normal wait, that's a reasonable way too. But generally, you will never need to use it.


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

...