状态机
前言
前几天接触到一个概念,叫状态机。就马上到网上搜索了一下这个概念。经过网上的学习,对状态机有了一定的认识,写下这篇博客介绍一下。
简介
状态机,表示某几种状态之间的切换。
因为状态机的状态是有限的,所以一般上也叫有限状态机(Finite State Mache)。
在我们做开发的过程中,如果有逻辑关系比较混乱的,我们就可以考虑使用有限状态机来解决问题。
参考链接:
https://www.cnblogs.com/jiangzhaowei/p/9129024.html
示例
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
/* FSM(Finite State Machine),有限状态机
* date: 2019.12.06
* author: chasenzhang
*/
typedef enum state
{
state_1 = 0,
state_2,
state_3,
state_num,
}state_t;
typedef enum event
{
event_1 = 0,
event_2,
event_3,
event_num,
}event_t;
typedef struct FSM_tables_s
{
int cur_state;
int event;
void (*action)();
int next_state;
}FSM_tables_t;
void action()
{
printf("state has change!\n");
}
FSM_tables_t FSM_Tables[] =
{
{state_1, event_1, action, state_2},
{state_2, event_2, action, state_3},
{state_3, event_3, action, state_1},
{state_3, event_2, action, state_1},
};
void event_handle(state_t *state, event_t *event)
{
int i = 0;
int num = sizeof(FSM_Tables)/sizeof(FSM_Tables[0]);
for (i = 0; i < num; i++)
{
if (*state == FSM_Tables[i].cur_state && *event == FSM_Tables[i].event)
{
*state = FSM_Tables[i].next_state;
FSM_Tables[i].action();
break;
}
}
}
int main()
{
printf("this is test!\n");
int num = 6;
state_t state = 0;
event_t event = 0;
while (num--)
{
printf("state = %d, event = %d\n", state, event);
event_handle(&state, &event);
event++;
state %= state_num;
event %= event_num;
sleep(1);
}
return 0;
}
运行结果
this is test!
state = 0, event = 0
state has change!
state = 1, event = 1
state has change!
state = 2, event = 2
state has change!
state = 0, event = 0
state has change!
state = 1, event = 1
state has change!
state = 2, event = 2
state has change!