Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...