pasis/libcouplet — pull request #6 by horazont (2013-01-22 17:17:23+00:00)
Title: High CPU usage during idle

libcouplet has a quite high CPU usage during idle. While this can be fixed by increasing ``DEFAULT_TIMEOUT`` (50ms gives fine timings for timed handlers and an acceptable CPU usage), there should be other ways, regarding the fact that we have now threads.

I imagine that one could offload the timing of the timed handlers to another thread, which just wakes up the main thread and gets woken up upon addition of another timer.

The main thread could stay in its select() call, where the timer thread would signal the arrival of a timer somehow.

The timer thread would have a pretty simple loop. It would calculate the time until the next timed event and sem_wait (wtih the time as the timeout) until then on a semaphore; If the main thread changes the order of events (e.g. by inserting one), it could flag the semaphore so that the thread can recalculate.

If a timer gets fired, one would have to signal that to the main thread. One could either use a unix socket to communicate between the two. It could send the pointer to a linked list of event handlers to fire, which is to be freed by the main thread (to avoid racing on the list).

This is obviously a lot to implement, and I might have a go on that in a few weeks when I have time again. For now, I'd suggest to increase ``DEFAULT_TIMEOUT`` to 50ms in the main distribution as that'll be more than enough for most applications. Note that a full implementation would make timeouting obsolete, except to trigger for other events which cannot be caught that way.

Comments?