Busy Waiting

An AntiPattern. Also known as "spinning."

This is a process whereby the CPU spends most of its time in a tight loop waiting for a device to become ready. Used by newbies and people not familiar with the myriad ways to avoid this in real time operating systems.


Not always an AntiPattern. Sometimes critical sections, events, context switches, etc. impose unacceptable overhead. That's when you need a SpinLock. Or when those kinds of sync. objects may not be available on the platform you are using. -- JamesTwine

It's also useful if the worst case busy wait is just a few machine cycles, e.g. when talking to a memory-mapped hardware device; sometimes the only available suspend mechanisms have much too large of a granularity.

But in software-only single processor systems, there's never any point in BusyWaiting, because the resource will only become free once another thread/process runs, which is only possible once the current thread yields explicitly or due to quantum expiration, so one should go ahead and yield the processor immediately rather than pointlessly BusyWaiting.

Note that the critical difference between BusyWaiting and Polling is that Polling includes blocks of time where the CPU is free to do other things. For example:

BusyWaiting:

  while ( MyFileIsNotReady() )
  {
    //Do nothing
  }

Polling:
  while ( MyFileIsNotReady() )
  {
     Sleep(1000);
  }

Polling is sometimes necessary and sometimes a good idea; BusyWaiting is very rarely necessary and is almost always a bad idea.


See: CooperativeThreading, SynchronizationStrategies

CategoryRealTime


EditText of this page (last edited July 1, 2005) or FindPage with title or text search