Take below as example, notice async mostly used in multi-thread,
// FILE NAME: a.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
typedef void (*pcb)(int a);
typedef struct parameter
{
int a;
pcb callback;
} parameter;
void *callback_thread(void *p1)
{
//do something
parameter *p = (parameter *)p1;
while (1)
{
printf("GetCallBack print! \n");
sleep(3); //delay 3s
p->callback(p->a);
}
}
extern int SetCallBackFun(int a, pcb callback)
{
printf("SetCallBackFun print! \n");
parameter *p = malloc(sizeof(parameter));
p->a = 10;
p->callback = callback;
pthread_t thing1;
pthread_create(&thing1, NULL, callback_thread, (void *)p);
pthread_join(thing1, NULL);
}
// FILE NAME: b.c
#include "boo.c"
#include <stdio.h>
void fCallBack(int a)
{
//do something
printf("a = %d\n",a);
printf("fCallBack print! \n");
}
int main(void)
{
SetCallBackFun(4,fCallBack);
return 0;
}
Output is below,
SetCallBackFun print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
a = 10
fCallBack print!
GetCallBack print!
...
In terms of calling function, there are three types: sync, back, and async.
The tricky thing is the last two are highly correlated, why is that?
Perhaps a graph would make it clear, i.e.
