热门问题
时间线
聊天
视角

事件驱动有限状态机

来自维基百科,自由的百科全书

Remove ads

在计算机科学中,有限状态机(FSM)是事件驱动的,若从一个状态到另一个状态的转换是由事件或是讯息所驱发的,这和有限状态机一词出自的语法分析理论相反,其中将状态机描述为消费字元或是记号(tokens)的机器。

多半有限状态机是一个线程或行程,是较大应用程式的一部分,需要和其他程式通讯。例如,电信通讯协定大部份都会用事件驱动有限状态机来表示。

C语言的例子

以下程式描述一个简单汽车收音机系统的状态机,基本上是一个读取事件的无穷回圈,状态机有二个状态:收音机模式,以及CD模式。其事件有“模式切换”(收音机模式和CD模式之间的切换)以及“下一个”(下一个广播电台或是CD的下一轨)。

/********************************************************************/
#include <stdio.h>

/********************************************************************/
typedef enum {
        ST_RADIO,
        ST_CD
} STATES;

typedef enum {
        EVT_MODE,
        EVT_NEXT
} EVENTS;

EVENTS readEventFromMessageQueue(void);

/********************************************************************/
int main(void)
{
  /* Default state is radio */  
  STATES state = ST_RADIO;
  int stationNumber = 0;
  int trackNumber = 0;

  /* Infinite loop */
  while (1)
  {
    /* Read the next incoming event. Usually this is a blocking function. */
    EVENTS event = readEventFromMessageQueue();

    /* Switch the state and the event to execute the right transition. */
    switch (state)
    {
      case ST_RADIO:
        switch (event)
        {
          case EVT_MODE:
            /* Change the state */
            state = ST_CD;
            break;
          case EVT_NEXT:
            /* Increase the station number */
            stationNumber++;
            break;
        }
        break;

      case ST_CD:
        switch (event)
        {
          case EVT_MODE:
            /* Change the state */
            state = ST_RADIO;
            break;
          case EVT_NEXT:
            /* Go to the next track */
            trackNumber++;
            break;
        }
        break;
    }
  }
}
Remove ads

相关条目

延伸阅读

  • Peatman, John B. Microcomputer-based Design. New York: McGraw-Hill, Inc. 1977. ISBN 0-07-049138-0.
  • Brookshear, J. Glenn. Theory of Computation: Formal Languages, Automata, and Complexity. Redwood City, California: Benjamin/Cummings Publish Company, Inc. 1989. ISBN 0-8053-0143-7.
Loading related searches...

Wikiwand - on

Seamless Wikipedia browsing. On steroids.

Remove ads