操作系统——什么是程序和编译器
1 状态机
1.1 什么是状态机
A state machine is a mathematical abstraction used to design algorithms. A state machine reads a set of inputs and changes to a different state based on those inputs. A state is a description of the status of a system waiting to execute a transition.
状态机是用于设计算法的数学抽象。
状态机读取一组输入,并根据这些输入更改为不同的状态。
状态是对等待执行转换的系统状态的描述。
一句话: 状态机,就是一个动态系统,就是一个简单的离散微分方程。
1.2 举例
从数字逻辑电路来讲:
- 状态 = 寄存器保存的值(flip-flop)
- 初始状态 = Reset(implementation dependent)
- 迁移 = 组合逻辑电路计算寄存器下一周期的值
下面就是一个 state machine:
X
′
=
¬
X
∧
Y
Y
′
=
¬
X
∧
¬
Y
X^{'}=\neg X \land Y \\ Y^{'}= \neg X \land \neg Y \\
X′=¬X∧YY′=¬X∧¬Y
朋友们,这里
X
′
X^{'}
X′ 代表下一周期的
X
X
X 的状态。同理,
Y
′
Y^{'}
Y′ 代表下一周期的
Y
Y
Y 的状态。
X | Y | ¬ X \neg X ¬X | ¬ Y \neg Y ¬Y | X ′ = ¬ X ∧ Y X^{'}=\neg X \land Y X′=¬X∧Y | Y ′ = ¬ X ∧ ¬ Y Y^{'}= \neg X \land \neg Y Y′=¬X∧¬Y |
---|---|---|---|---|---|
0 | 0 | 1 | 1 | 0 | 1 |
0 | 1 | 1 | 0 | 1 | 0 |
1 | 0 | 0 | 1 | 0 | 0 |
这个 state machine 的 state 有亮种:00、01、10,就按照下面的方式不断转圈圈。
下面是用C语言实现的程序:
#include <stdio.h>
#define REGS_FOREACH(_) _(X) _(Y)
#define RUN_LOGIC X1 = !X && Y; \
Y1 = !X && !Y;
#define DEFINE(X) static int X, X##1;
#define UPDATE(X) X = X##1;
#define PRINT(X) print(#X " = %d;", x);
int main(){
REGS_FOREACH(DEFINE);
while(1){
RUN_LOGIC;
REGS_FOREACH(PRINT);
REGS_FOREACH(UPDATE);
putchar('\n');
sleep(1);
}
}
上面宏定义的语言展开后,其实是这样的:
int mian(){
static int X, X1;
static int Y, Y1;
while(1){
X1 = !X && Y; Y1 = !X && !Y;;
printf("X" " = %d;", X); printf("Y" " = %d;", Y);;
X = X1; Y = Y1;
putchar('\n'); sleep(1);
}
}