Callback
Callback
What is callback
"A Callback is a piece of executable code that is passed as an argument to other code, which is expected to call back(execute) the argument at some convenient time." -- wikipedia
Different programming languages have different implement of callback, but they are often implemented with subroutines, lambda expression, blocks, or function pointer.
There are two kinds of callbacks:
(1) Blocking callbacks(also synchronous callbacks): - Blocking callbacks are invoked before a function returns. - Blocking callbacks often, but not always, reply on a single thread, so blocking callbacks use less for synchronization or delegating work to another thread. (1) Deferred callbacks(also asynchronous callbacks): - Deferred callbacks are invoked after a function returns. - Deferred callbacks are often used in the context of I/O operations or event handling. - Deferred callbacks imply the existence of multiple threds.
Some implements tips
First of all, we should know that to implement a callback, we should let a function to be a argument passed to another function, and being invoked.
Here is some implements:
(1) Using function pointer: - C/C++ and Pascal allow function pointer to be a argument. Example of C
(2) Language-support function argument - Suching as Python, JavaScript, Perl and Php, language support a function to be a argument passed to another function. An example of Python:
- CLI Languages use a delegate to implement callback.
- Functional languages supporting a function passed to other functions as a callback.(See the Python example above). By the way, functional language also allow you to pass a function to other function as data, or return from the functions.
- Pure Object-oriented programming language like Java implement callback by passing an instance of an abstract class or interface. Then the receiver call the methods of the class or interface. This looks like the observer pattern
Some example from network
- JavaScript can pass a function as argument.
- C language