By default, eventhandler_deregister() blocks until it reaches some point
where no threads are invoking the event. At this point, it knows that
- no threads are currently executing the handler,
- some thread has freed the eventhandler structure by virtue of having called eventhandler_prune_list(),
so it is safe to return.
Suppose a thread is trying to deregister an event handler. A different
thread prunes it, and wakes up the first thread. Before the first
thread runs, a third thread grabs the event handler lock, and starts
executing handlers. The first thread observes el_runcount > 0, and goes
back to sleep. The third thread sees no event handlers to prune, and
doesn't wake up the first thread, which sleeps forever.
This change fixes the race and tries to make eventhandler_invoke() more
efficient: keep a count of the number of dead list entries and only
prune the list if there is at least one dead entry. Also, in
eventhandler_deregister(), we only need to sleep if some dead entries
are present, rather than sleeping whenever some thread is running
handlers.