【发布时间】:2014-01-09 05:02:41
【问题描述】:
我正在寻找实现 FSM 的方法,这导致我第一次遇到协程。
我看到了几个示例(here、here 和here),它们暗示状态机可以由单个协程实现。然而,我注意到所有这些机器的共同点是,不包括循环,它们是树——也就是说,从起始节点到每个其他节点只有一条路径(不包括循环)——并且很好地映射到层次控制由嵌套的ifs 提供的流。我试图建模的状态机至少有一个状态,从起始节点到它的路径不止一条(如果消除了循环,它就是一个有向无环图)。而且我无法想象什么样的控制流(除了gotos)可以实现这一点,或者是否有可能。
或者,我可以使用单独的协程来处理每个状态并让步给某种调度程序协程。但是,我认为在此设置中使用协程相对于常规函数没有任何特别的好处。
这是一个我无法建模的简单状态机:
A --'a'--> B
A --'b'--> C
B --'a'--> C
B --'b'--> A
C --'a'--> A
C --'b'--> B
这就是我目前所拥有的。最终实现将在 C++ 中使用 Boost,但我使用 Python 进行原型设计。
#!/usr/bin/python3
def StateMachine():
while True:
print(" Entered state A")
input = (yield)
if input == "a":
print(" Entered state B")
input = (yield)
if input == "a":
# How to enter state C from here?
pass
elif input == "b":
continue
elif input == "b":
print(" Entered state C")
input = (yield)
if input == "b":
continue
elif input == "a":
# How to enter state B from here?
pass
if __name__ == "__main__":
sm = StateMachine()
sm.__next__()
while True:
for line in input():
sm.send(line)
能否修复这个协程以正确建模状态机?还是我必须采取其他方式?
【问题讨论】:
标签: coroutine fsm state-machine