views:

185

answers:

3

I dont understand why Threads have to "sleep" if there is no event in the Application Run Loop. Does this save energy, or memory, or what else?

When there comes in an event from an source input, then it would wake up that Thread again to handle this event. After that, it would sleep again, for the case that there is no more event in the queue waiting to be processed.

Does someone have a good explanation for this sleeping issue?

+2  A: 

A sleeping thread allows an OS scheduler (a subsystem which allocates CPU time to threads) to run other threads.

Anton Gogolev
+2  A: 

It's not an issue. It's a good thing. What else would the main thread be doing? It shouldn't be processing long-running tasks - that would reduce the "snappiness" of the UI when a UI event comes in.

It shouldn't be tight-looping until an event comes in - that would take up processor time which can otherwise be sensibly used by other applications.

Sleeping (or rather waiting) is exactly what you want it to do - so it can wake up as soon as it has useful work to do, but otherwise doesn't impact the system.

Jon Skeet
+2  A: 

As others have said, putting the thread to sleep allows other threads to be executed.

I'll add that since you are probably referring to the iPhone (based on most of your other questions) this will also be useful even if no other threads need to run as the CPU power consumption will drop when it is idle.

Eric Petroelje