Home > Articles > Programming

  • Print
  • + Share This
From the author of Don't Poll

Don't Poll

Polling is a technique that's typically used to increase responsiveness. The CPU enters a short loop, repeatedly testing a condition until it becomes true. Because the CPU is busy, polling is almost always a bad idea if you care about power usage.

Most applications live in a multitasking environment. Since polling can take CPU time away from other apps, it has been discouraged in general for over a decade for I/O. On mobile platforms, it's often a good idea to take this rule a stage further. For example, AJAX-style apps regularly poll a web server for new events, but using a wireless network is a very good way of flattening a mobile device's battery. Replacing the polling with push notifications can give you big power savings. Use something like the Extensible Messaging and Presence Protocol (XMPP), WebSocket, or a custom protocol.

This concept is especially applicable for mutual exclusion locks (mutexes), most of which are implemented by using atomic test-and-set operations in userspace and polling a few times before calling into the kernel. On a single-processor machine, this polling will be faster only if it has a context switch in the middle. On a multicore machine, it can be much faster. But both cases involve using the CPU for a bit, while achieving nothing.

The mutex implementation on Darwin (used in the iPhone and desktop OS X) calls down into the kernel a lot more aggressively than any other mainstream UNIX variant does. This approach gives better power usage on single-core machines, such as the iPhone, but at the cost of a significant performance hit on desktop systems. It's amusing to read the marketing material for the amazing fast new kind of locks that Apple uses in Grand Central Dispatch—other platforms use exactly the same implementation in their general locking code.

  • + Share This
  • 🔖 Save To Your Account