Are Callbacks A Bad Idea?
Someone was asking me yesterday why I think that Callbacks are such a bad idea. Firstly let's define exactly what a Callback is in terms of computer programming in C, C++, or Java.
Many people use callbacks as a form of RPC. The user implements an abstract interface, in the OOP world, or a function pointer in the non-OOP world. When the underlying API needs to notify the calling application of an event then it calls the Callback function specified by the calling application. This is the crux of the problem, as I see it, the calling application specifies what action is to take place within the Callback and this is potentially very hazarous to the API's efficiency.
For example, what would happen if an API called a Callback and the Callback decided to sleep for 10 seconds? The API would loose control of the thread which called the Callback for that 10 seconds and could potentially be dead in the water unless it has other threads available for work. By definition a Callback needs to execute quickly otherwise the application risks slowing the API down. Unfortunately the application and the API may have two completely different ideas as to what quickly means.
Rather than use Callbacks I would propose that the use of Semaphores is far more sensible. Using a Semaphore you can notify a thread that an event has taken place without any risk to yourself that the notification will take any significant amount of time. If you use a Callback you have no way to predict how much time the Callback will require to execute and return control back to code which you have, the API author, control over. Note that I'm proposing the use of a Semaphore rather than simply a Synchronization Object, in Java, or an Event in Win32 since a Semaphore is capable of being triggered multiple times and retains the knowledge of how many times it was triggered, i.e. an Event is bistate, 0 or 1, true or false, however, a Semaphore maintains a reference count. This allows a Semaphore to be triggered for multiple events and for the application to service each of those events.
Have you had a callback problem in any of your programs?
Good luck with your inter-thread communication, if you have any additional thoughts please leave a comment or email your question, which you'd like me to answer for free, to Ben Dash at firstname.lastname@example.org