Page 1 of 1
[event loop] Why should a handler not do any registrations on its own event loop?
Posted: Thu Feb 01, 2024 11:54 am
by profeldoo
It says here:
https://docs.espressif.com/projects/esp ... ing-itself
In general, an event handler run by an event loop is not allowed to do any registering/unregistering activity on that event loop.
Why is that, or, why could it be a problem? I have skimmed the handler registration code and do not see any obvious reasons. So far, it works.
Re: [event loop] Why should a handler not do any registrations on its own event loop?
Posted: Fri Feb 02, 2024 8:54 am
by profeldoo
Re: [event loop] Why should a handler not do any registrations on its own event loop?
Posted: Fri Feb 02, 2024 2:23 pm
by MicroController
Yeah.
But the actual reason is that there can be multiple listeners for the same event; hence, the event handler task manages lists of listeners. To dispatch an event, it iterates over the list of corresponding event handlers and calls one after the other. If one event handler adds or removes another event handler, i.e. modifies the list while it is being iterated over, 'undefined' behaviour can occur; specifically, depending on the positions of handlers in the list, a handler that was just removed may or may not be executed afterwards for the current event, an event handler that was just added may or may not be executed for the current event.
Re: [event loop] Why should a handler not do any registrations on its own event loop?
Posted: Fri Feb 02, 2024 3:00 pm
by profeldoo
Thanks, good point.
So, a 'strong form' of the rule stated in the docs:
Do not register/unregister other handlers inside the handler itself.
would be:
Inside the handler, do not register/unregister other handlers to/from the event that just fired. You are allowed to register/unregister handlers to/from any other event.
Because then you are not modifying the list of handlers currently being looped over.
Re: [event loop] Why should a handler not do any registrations on its own event loop?
Posted: Sat Feb 03, 2024 3:24 pm
by MicroController
Yes, I think technically that'd be accurate - as of now.
But I'd be hesitant to state this in API documentation too, because it is very much dependent on the specifics of how the event handling task is implemented (i.e. internally using only one list for all handlers vs. one list per event type); and these specifics may well change at some point, breaking compatibility with code that relies on this behaviour.
So as a user, I'd go with what's documented to be able to update to later IDFs in the future without having to worry so much about checking for new bugs introduced through my reliance on undocumented features in previous versions.