close

When you meet, you learn it.

Before working, I never hear about "callback function".

But now, I use it almost everyday.

Why we use callback function?

It is a good question.

For an example, as follows:

When creating a thread, we can assign our callback function to the thread.

And then we can go to sleep.

When the thread complete the work, it could call the callback function.

We are wakeup by the thread.

It is a good mechanism for programmer.

Here is a code example


[Callback function example]

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

//Define Callback funtion type
typedef void (* CALLBACK) (int);
 
//My callback function
void MyCallback(int percentage)
{
    fprintf(stderr, "%dn%nn", percentage);
}
 
//Function will call callback function
void DoCallBack(int Counting, CALLBACK callback)
{
    int i;
    for(i=0; i<Counting; i++)
    {
        //Do Something
    }
    callback(i);
}
 
//Main Function
int main(void)

{
    DoCallBack(100, MyCallback);
    return 0 ;
}

arrow
arrow
    全站熱搜

    owenhuangtw 發表在 痞客邦 留言(0) 人氣()