Understand some summary of callback functions

The first time the callback function came into contact with this term was seen in the thread chapter of "Linux C Practical Programming". At that time, a program in condition.c did not understand very well, mainly because the function pthread_cleanup_push( ) was called, which The reason is that the occupied resources cannot be released due to the unforeseen program exit, which is usually solved by using a callback function. So I started to pay attention to the word callback function. I searched a lot of information on the Internet and learned a lot. In the end, I personally feel that it will play a great role in the future reading programs. Many codes, both foreign and domestic, will use callback functions, and there are many examples of the development of callback functions. So I feel that this thing may be used in the future, and I should understand it first.


pthread_cleanup_push( ) /pthread_cleanup_pop( )使用

Let’s see the big from the small. First of all, let’s talk about how I know this callback function from the thread.
pthread_cleanup_push( ) and pthread_cleanup_pop( ) must appear in pairs. There are two main exit methods in a thread, one is normal exit and the other is abnormal exit.
Active exit can use the pthread_exit() function, or return from the thread function can exit from the thread. Abnormal exit means that it exits when it is interfered by other threads or an error occurs.
Regarding the use of these two functions, please quote other people's things first, I feel that they have summed up very well.

pthread_cleanup_push()/pthread_cleanup_pop() adopts the first-in-last-out stack structure management. The void routine(void *arg) function is pushed into the cleanup function stack when calling pthread_cleanup_push(), and multiple calls to pthread_cleanup_push() will be in the cleanup function stack. Forms a chain of functions that are popped in the reverse order of being pushed on the stack when the chain of functions is executed. The execute parameter indicates whether to execute the function while popping up the cleanup function when pthread_cleanup_pop() is executed. If it is 0, it means not to execute it, and if it is not 0, it means to execute it; this parameter does not affect the execution of the cleanup function during abnormal termination.
pthread_cleanup_push()/pthread_cleanup_pop() is implemented as a macro, which is the macro definition in pthread.h: #define pthread_cleanup_push(routine,arg)
{ struct _pthread_cleanup_buffer _buffer;
_pthread_cleanup_push (&_buffer, (routine), (arg))# define pthread_cleanup_pop(execute)
_pthread_cleanup_pop (&_buffer, (execute)); }
Visible, pthread_cleanup_push() takes a "{", and pthread_cleanup_pop() takes a "}", so these two functions must appear in pairs, and must Only code sections located at the same level of the program can pass compilation. Actively call return in the thread host function. If the return statement is included in the pthread_cleanup_push()/pthread_cleanup_pop() pair, it will not cause the execution of the cleanup function, but will cause a segment fault.

Then at this time, when the unlocking is unsuccessful, or when the pthread_cond_wait( ) function in the mutex is unlocked and re-locked, an exception occurs in this function, causing the execution of the wait function to be cancelled and the unlocking is unsuccessful. , you can use the first parameter in pthread_cleanup_push, a function pointer points to the unlock function, and the entry address of the unlock function is passed in. This function is called when the unlock is unsuccessful.

So it can be seen from this that the function called by the callback function needs certain conditions to be executed. If the condition is true, the function in the callback function will be called, and if the condition is not true, it will not be called.

Understanding callback functions

A callback function is a function by calling a function pointer. When a certain condition is reached, it implements a function of the function pointed to by the function pointer through the function pointed to by the function pointer. The implementation of the callback function is realized through the operation of the callback mechanism. It is easy to understand that a function contains a function pointer in its formal parameters, and the function that realizes the whole process by manipulating this function pointer is the callback function (note the division of subject, predicate and object...)

Put the definition on Baidu:

If you pass a pointer (address) of a function as a parameter to another function, when this pointer is used to call the function it points to, we say this is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs to respond to the event or condition.
Mechanism: (1) Define a callback function; (2) The party providing the function implementation registers the function pointer of the callback function to the caller during initialization; (3) When a specific event or condition occurs, the caller uses the function pointer to call the callback function pair. event is processed.

Corresponding to the pthread_cleanup_push()/pthread_cleanup_pop() above, you can actually understand the benefits of this mechanism. It is a function that is first passed in and then waits for a suitable time to be called. It is very flexible between applications and libraries, and I also learned about it on Zhihu, but its application is not between applications and libraries. It feels a bit complicated after reading it, but it quotes a simple and straightforward image. metaphor.

Chang Xiling
A geeky nerd.
Included in the editor's recommendation · 2734 people agreed with this answer
You went to a store to buy something, and it happened that the thing you wanted was out of stock, so you left your phone number with the clerk, and after a few days the store When there is stock in the store, the clerk calls you, and then you go to the store to pick up the goods after you receive the call. In this example, your phone number is called the callback function. If you leave the phone number to the clerk, it is called the registration callback function. When the store has stock later, it is called triggering the callback-related event. When the clerk calls you, it is called calling the callback function. Your trip to the store to pick up the item is called responding to a callback event.
Posted on 2011-08-06
2.7K
96 Comments

After reading a lot of comments (the difference between hardware interrupts and callbacks is also drawn later...) I feel that the callback function is generally a process of calling back to a higher level, from the bottom to the top. The callback function is an intermediate transition layer.
For example, from pthread_cleanup_push( )/pthread_cleanup_pop( ), in the main function.

pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
pthread_mutex_lock(&mut);
count++;
pthread_mutex_unlock(&mut);
pthread_cleanup_pop(0);

First, the main function is the first layer, and the lock and unlock function is also the first layer function. Then both push and pop are the second layer, so the first layer calls the second layer, and the second layer calls back to execute the first layer. The function. This is a callback mechanism.

#include <stdio.h>

void printWelcome(int len)
{
       printf("欢迎欢迎 -- %d/n", len);
}

void printGoodbye(int len)
{
       printf("送客送客 -- %d/n", len);
}

void callback(int times, void (* print)(int))
{
       int i;
       for (i = 0; i < times; ++i)
       {
              print(i);
       }
       printf("/n我不知道你是迎客还是送客!/n/n");
}
void main(void)
{
       callback(10, printWelcome);
       callback(10, printGoodbye);
       printWelcome(5);
}

Then refer to a callback function of others. At this time, the function callback function is layer B, the main function and print* function are layer A, layer A calls the callback function callback function of layer B, and the callback function of layer B calls the implementation of layer A. function print.

So through two examples, the function of this middle layer, the callback function is a bridge. Just like the example above, the example of the salesperson leaving the number, if you do not register the callback function and leave the phone number, even if the goods arrive, you will not be contacted. The above are some of the information I found on the Internet, and my understanding.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326362699&siteId=291194637