Aaron2932

导航

C语言支持闭包

前言

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 *)&para2, (void *)&para2, 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 *)&para1;
    para.para2 = (void *)&para2;
    Loop(duration, maxTimes, &para);
}

int main()
{
    Demo_LoopDoV1();
    Demo_LoopDoV2();

    return 0;
}

posted on 2022-11-28 03:45  Aaron2932  阅读(149)  评论(0编辑  收藏  举报