有限状态机示例

有限状态机

有限状态机是一种思想,常用于控制流程的代码中,用于状态的切换。下面是示例,在centos7上可以编译运行。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define STATE_S1 1
#define STATE_S2 2
#define STATE_S3 3

void *getInfo(void *arg);
void swap_state1_handler(void);
void swap_state2_handler(void);
void swap_state3_handler(void);
void swap_process(void);

typedef struct{
int current_state;
int next_state;
}NODE;

typedef void (*SWAP_CALLBACK)(void);

struct swap_event_t{
int swap_state;
SWAP_CALLBACK funcptr;
};

static struct swap_event_t swap_event[] =
{
{STATE_S1,swap_state1_handler},
{STATE_S2,swap_state2_handler},
{STATE_S3,swap_state3_handler},
};

int swap_event_count = sizeof(swap_event)/sizeof(swap_event[0]);

NODE node =
{
.current_state = 1,
.next_state = 1,
};

int main()
{
pthread_t thread_id1;

pthread_create(&thread_id1,NULL,getInfo,NULL);

while(1)
{
sleep(1);
swap_process();
}

return 0;
}

void *getInfo(void *arg)
{
int temp;
while(1)
{
scanf(“%d”,&temp);
node.next_state = temp;
}
}

void swap_process(void)
{
int i=0;
for(i =0;i<swap_event_count;i++)
{
if(node.current_state == swap_event[i].swap_stae)
{
swap_event[i].funcptr();
break;
}
}
}

void swap_state1_handler(void)
{
printf(“current state is %d\n”,node.current_state);
node.current_state = node.next_state;
}

void swap_state2_handler(void)
{
printf(“current state is %d\n”,node.current_state);
node.current_state = node.next_state;
}

void swap_state3_handler(void)
{
printf(“current state is %d\n”,node.current_state);
node.current_state = node.next_state;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值