In this reprinted #altdevblogaday in-depth piece, Valve Software's Bruce Dawson explains why busy waiting is rarely a good idea right now, and will become an even worse idea in the FIFA Coins future."I want to say, in all seriousness, that a great deal of harm is being done in the modern world by belief in the virtuousness of WORK, and that the road to happiness and prosperity lies in an organised diminution of work."In the past few years,

 

I have encountered many examples of code that spins in trove flux a busy loop, doing nothing useful for dozens of milliseconds. I've looked at dozens of xperf traces from customer machines that show both busy waiting and CPU starvation.There are many misconceptions about the costs and benefits of busy waiting, and I want to explain emphatically why busy waiting is rarely a good idea, is a worse idea now than in the past, and will become an even worse idea in the future.The

 

to busy waitA simple way of providing mutual exclusion is to have flag which a thread can atomically test-and-set, using something like InterlockedCompareExchange. If the flag is zero and you are able to atomically set it to one then you 'own' that critical region and you can safely execute your code.If you write your own lightweight mutex, you have to be careful to avoid reordering problems, but the basics of guaranteeing mutual exclusion are actually quite straightforward.The

 

is, what happens when somebody else owns the lock? You need to wait for them to release the lock – but how?One option is to wait on a semaphore. That puts you to sleep until the lock is released. That is good. That is appropriate. That is the whole freakin' point of this article. So do that. But first I want to explain why developers sometimes don't like waiting on a semaphore.Waiting on a semaphore means calling out to the kernel (expensive), context switching away from your thread to https://www.mmogo.com/