前言
c语言不支持闭包函数,因此需要通过参数结构体保存所有参数,将上下文传递给业务
概述
下面是一个例子,用于重试
#include <stdio.h>
#include <unistd.h>
typedef enum
{
E_SYNC_LOOP_REG,
} E_SYNC_LOOP_DO;
// when return 0, indict false, otherwise indict true, will break
typedef int (*FnLoopCall)(void *para1, void *para2, void *para3);
typedef struct
{
// int (*fnCall)(void *para1, void *para2, void *para3);
FnLoopCall fn;
void *para1;
void *para2;
void *para3;
} LoopDoPara;
void Loop(int duration, int times, LoopDoPara *para)
{
int ret;
int i;
for (i = 0; i < times; i++)
{
ret = para->fn(para->para1, para->para2, para->para3);
if (ret == 0)
{
break;
}
printf("current retry (%d)\n", i);
sleep(duration);
/* code */
}
return;
}
int mayBeFail(void *para1, void *para2, void *para3)
{
int a = *((int *)para1);
int b = *((int *)para2);
printf("para1(%d) para2(%d)\n", a, b);
return -1;
}
void Demo_LoopDoV1()
{
printf(">>>>>>>current retry in v1\n");
int i;
int ret;
int maxTimes = 4;
int duration = 1;
int para1 = 1;
int para2 = 2;
for (i = 0; i < maxTimes; i++)
{
ret = mayBeFail((void *)¶2, (void *)¶2, NULL);
if (ret == 0)
{
break;
}
printf("current retry (%d)\n", i);
sleep(duration);
/* code */
}
}
void Demo_LoopDoV2()
{
printf(">>>>>>>current retry in v2\n");
int maxTimes = 4;
int duration = 1;
LoopDoPara para = {0};
para.fn = mayBeFail;
int para1 = 1;
int para2 = 2;
para.para1 = (void *)¶1;
para.para2 = (void *)¶2;
Loop(duration, maxTimes, ¶);
}
int main()
{
Demo_LoopDoV1();
Demo_LoopDoV2();
return 0;
}
标签:闭包,para,int,void,支持,C语言,para2,para1,duration
From: https://www.cnblogs.com/aaron2932/p/16931229.html