状态机教程 [英] state machines tutorials

查看:280
本文介绍了状态机教程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道是否有人知道互联网发展状态机上的一些好的教程。或电子书?

I am just wondering if anyone know of some good tutorials on the Internet for developing state machines. Or ebooks?

我开始对状态机工作,只是需要一般的东西让我开始。

I am starting working on state machines and just need something general to get me started.

推荐答案

状态机在C很简单,如果你使用的函数指针。

State machines are very simple in C if you use function pointers.

基本上你需要2阵列 - 一个状态函数指针和一个状态转换规则。每个州函数返回code,可以通过国家和返回code查找状态转移表中查找下一个状态,然后就执行它。

Basically you need 2 arrays - one for state function pointers and one for state transition rules. Every state function returns the code, you lookup state transition table by state and return code to find the next state and then just execute it.

int entry_state(void);
int foo_state(void);
int bar_state(void);
int exit_state(void);

/* array and enum below must be in sync! */
int (* state[])(void) = { entry_state, foo_state, bar_state, exit_state};
enum state_codes { entry, foo, bar, end};

enum ret_codes { ok, fail, repeat};
struct transition {
    enum state_codes src_state;
    enum ret_codes   ret_code;
    enum state_codes dst_state;
};
/* transitions from end state aren't needed */
struct transition state_transitions[] = {
    {entry, ok,     foo},
    {entry, fail,   end},
    {foo,   ok,     bar},
    {foo,   fail,   end},
    {foo,   repeat, foo},
    {bar,   ok,     end},
    {bar,   fail,   end},
    {bar,   repeat, foo}};

#define EXIT_STATE end
#define ENTRY_STATE entry

int main(int argc, char *argv[]) {
    enum state_codes cur_state = ENTRY_STATE;
    enum ret_codes rc;
    int (* state_fun)(void);

    for (;;) {
        state_fun = state[cur_state];
        rc = state_fun();
        if (EXIT_STATE == cur_state)
            break;
        cur_state = lookup_transitions(cur_state, rc);
    }

    return EXIT_SUCCESS;
}

我不把 lookup_transition()的功能,因为它实在是微不足道。

I don't put lookup_transition() function as it is trivial.

这是我多年做状态机的方式。

That's the way I do state machines for years.

这篇关于状态机教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆