1.回调函数是啥?
回调函数:就是一种将双向依赖改为单向依赖的好工具。是一种在定义的模块不运行,交给另外一个模块运行的函数。
补充一个基本概念:【解引用】
解引用 "*"的作用是引用指针指向的变量值,引用其实就是引用该变量的地址,"解"就是把该地址对应的东西解开,解出来,就像打开一个包裹一样,那就是该变量的值了,所以称为"解引用"。
参考网址:https://blog.csdn.net/synapse7/article/details/10260339
导入demo:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
/*********************************************
*
* test function:利用多线程测试回调函数
*
* ******************************************/
void *cb(void *arg){
printf("call back running, %u\n",pthread_self()); //获取本线程的id
return NULL;
}
int main(void){
//创建两个线程
pthread_t tid;
pthread_create(&tid,NULL,cb,NULL);
pthread_t tid2;
pthread_create(&tid2,NULL,cb,NULL);
/*用来等待一个线程的结束,线程间同步的操作pthread_join*/
pthread_join(tid,NULL);
pthread_join(tid2,NULL);
}
注:man pthread_create
SYNOPSIS
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
Compile and link with -pthread.
DESCRIPTION
The pthread_create() function starts a new thread in the calling
process. The new thread starts execution by invoking start_routine();
arg is passed as the sole argument of start_routine().
The new thread terminates in one of the following ways:
* It calls pthread_exit(3), specifying an exit status value that is
available to another thread in the same process that calls
pthread_join(3).
二 、常见的回调函数
void (*p)(void);//函数指针,只能指向无参,无返回值的函数
void (*p1)(int,int);//另一个函数指针,能够指向两个整形参数,没有返回值
void (*p2)(int); //函数指针,指向一个有1个整形的参数
void *(*p3)(int *);//只能指向这样的函数 void *fun(int *a);
//函数指针赋值,必须格式(函数头)相同
p=fun1; //让p这个指针指向fun1的整个函数(函数就是你一个代码块,这个代码块执行到最后会返回)
p();//函数指针的执行,实际及就是他指向的函数对象的执行
(*p)() ;//原始的运行方法,表示通过*拿到所指向的是的对象(解引用)
三、回调函数demo
1.主函数 a.c
#include <stdio.h>
#include <stdio.h>
extern void(*step)(void);
void myfunc(void)
{
printf("testing\n");
}
int main()
{
step=myfunc;
run();
}
2、run.c
#include <unistd.h>
//定义一个函数指针
void (*step)(void)=NULL;
void run()
{
int c=0;
while(1){
if(step!=NULL){
step();
}
c++;
sleep(1);
}
}
gcc a.c run.c ./a.out
#include <stdio.h>
//返回值
typedef int (*callbac)(int,int);
//回调函数
int ADD(callbac p,int a,int b){
return (*p)(a,b);
}
int add(int a,int b)
{
return a+b;
}
int main()
{
printf("%d\n",add(1,2));
printf("%d\n",ADD(add,1,2));
return 0;
}