What is a callback function?

Source: Internet
Author: User
What is a callback function?


Let's go around a little way to answer this question.

Programming is divided into two categories: System programming (Systems programming) and application programming (application programming). The so-called system programming, simply speaking, is to write a library, and application programming is to use a variety of written libraries to write a function of the program, that is, the application. The system programmer will leave some interfaces for the libraries that they write, namely the API (Application programming interface, application programming Interface) for the application programmer to use. So in the abstraction layer diagram, the library is underneath the application.

When the program runs, typically, the application (application programs) often invokes the pre-prepared functions in the library through the API. However, some library functions require the application to pass it a function, which is called at the appropriate time to accomplish the target task. The passed-in, then-called function is called a callback (callback function).

For example, there is a hotel with wake-up service, but it is required to decide how to wake up. Can be a room phone, or send a waiter to knock on the door, sleep afraid of delay, you can also ask to pour water basin on their head. Here, the "Wake Up" behavior is provided by the hotel, which is equivalent to the library function, but the method of waking up is determined by the traveler and tells the hotel, that is, the callback function. And the traveler tells the hotel how to wake up their actions, that is, the callback function to transfer the function of the functions, called the registration callback function (to register a callback functions). As shown (image source: Wikipedia):


As you can see, the callback function is usually at the same level of abstraction as the application (because the callback function passed in is determined at the application levels). And the callback becomes a high-level call to the bottom, the bottom back to call the high-level process. (I think) this should be the earliest application of the callback, and the reason why it is named.

Advantages of the callback mechanism

As you can see from the example above, the callback mechanism provides a lot of flexibility. Note that from now on, we have renamed the library function in the diagram as an intermediate function because the callback is not just used between the application and the library. At any time, you can take advantage of callbacks as long as you want flexibility similar to the situation above.

How is this flexibility implemented? At first glance, the callback appears to be just a call between functions, but a careful thought can reveal a key difference between the two: in the callback, we use a certain way to pass the callback function as a parameter into the intermediate function. It can be understood that the intermediate function is incomplete before passing in a callback function. In other words, the program can determine and change the behavior of the intermediate function at run time by registering different callback functions. This is much more flexible than a simple function call. Take a look at the following simple example of a callback written by Python:

' even.py ' #回调函数1 # generates an even def double (x) in 2k form:    return x * 2    #回调函数2 # generates an even def quadruple (x) in 4k form:    return x * 4 ' callback_demo.py ' from even import * #中间函数 # accepts an even-numbered function as a parameter # returns an odd Def getoddnumber (K, getevennumber): return    1 + Getevennumber (k)    #起始函数, here is the main function of the program Def Main ():        k = 1    #当需要生成一个2k +1 form of odd when    i = Getoddnumber (k, double)    print (i)    #当需要一个4k +1 odd when    i = Getoddnumber (k, quadruple)    print (i)    #当需要一个8k +1 odd-form    I = Getoddnumber (k, Lambda x:x * 8)    print (i)    if __name__ = = "__main__":    Main ()


Run ' callback_demp.py ', the output is as follows:

3
5
9

In the code above, the


gives ' getoddnumber ' different callback functions, and it behaves differently, which is the advantage of the callback mechanism. It is worth mentioning that the third callback function above is an anonymous function.

Easy-to-ignore third-party

through the above discussion, the middle function and the callback function are two necessary parts of the callback, but people tend to ignore the third corner in the callback, which is the caller of the intermediate function. In most cases, this caller can be equated with the main function of the program, but in order to represent the difference, I call it the starting function (as shown in the comments in the code above). The reason

specifically emphasizes this third party is because I get an impression when I read related articles online, and many people simply interpret it as a round-trip call between two individuals. For example, many Chinese web pages explain the word "callback" (callback) by saying, "If you call me, I'll call you back." I did not find the source of the English word. I personally speculate that many people think of the start function and the callback function as one, there are about two reasons: first, it may be the "callback" of the name of the misleading; second, what kind of callback function is passed to the intermediate function is decided in the starting function. In fact, the callback is not the interaction between "you and Me", but the three-party linkage of ABC. With this clear concept, it is not easy to confuse errors when implementing callbacks in your own code.

In addition, callbacks actually have two types: a blocking callback and a deferred callback. The difference between the two is that: in a blocking callback, the call to the callback function must occur before the start function returns, whereas in a deferred callback, the callback function may be called after the start function returns. This is not intended to be a more in-depth discussion of these two probabilities, but to illustrate the importance of emphasizing the starting function. Many articles on the Internet, referring to these two concepts, it is only general to say that the blocking callback occurs before the return of the keynote function, but there is no clear whether the central function is the starting function or the middle function, it is confusing, so here specifically explained. Also, note that the examples in this article are blocking callbacks. The deferred callback is usually involved in multithreading, and I'm not fully aware of it, so there's not much to say here.

here in its own summary, usually we write a function, the function will be used in the system of the various API functions, and then call their own writing function when needed; now, in turn, let's write a function that doesn't call the system's API. Then we call the already written function through the system API, so that the function we write becomes callback functions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.