from state_machine import State, Event, acts_as_state_machine, after, before, InvalidStateTransition# 状态机@acts_as_state_machineclassProcess:# 定义各种状态 created =State(initial=True)# 指定状态机的初始状态 waiting =State() running =State() terminated =State() blocked =State() swapped_out_waiting =State() swapped_out_blocked =State()# 定义状态转换,每个转换都是一个 Event,使用 from_states 和 to_state 来定义一个可能的转换 wait =Event(from_states=(created, running, blocked, swapped_out_waiting), to_state=waiting) run =Event(from_states=waiting, to_state=running) terminate =Event(from_states=running, to_state=terminated) block =Event(from_states=(running, swapped_out_blocked), to_state=blocked) swap_wait =Event(from_states=waiting, to_state=swapped_out_waiting) swap_block =Event(from_states=blocked, to_state=swapped_out_blocked)# 进程独有的信息,比如名称def__init__(self,name): self.name = name# 用于在转换之前或之后执行动作@after('wait')defwait_info(self):print('{} entered waiting mode'.format(self.name))@after('run')defrun_info(self):print('{} is running'.format(self.name))@before('terminate')defterminate_info(self):print('{} terminated'.format(self.name))@after('block')defblock_info(self):print('{} is blocked'.format(self.name))@after('swap_wait')defswap_wait_info(self):print('{} is swapped out and waiting'.format(self.name))@after('swap_block')defswap_block_info(self):print('{} is swapped out and blocked'.format(self.name))# 分别是 Process 实例、Event 实例、事件的名称deftransition(process,event,event_name):try:event()except InvalidStateTransition as err:print('Error: transition of {} from {} to {} failed'.format(process.name, process.current_state, event_name))# 展示进程当前(激活)状态的一些基本信息defstate_info(process):print('state of {}: {}'.format(process.name, process.current_state))defmain(): RUNNING ='running' WAITING ='waiting' BLOCKED ='blocked' TERMINATED ='terminated' p1, p2 =Process('process1'),Process('process2') [state_info(p)for p in (p1, p2)]# 不断进行状态转换print()transition(p1, p1.wait, WAITING)transition(p2, p2.terminate, TERMINATED) [state_info(p)for p in (p1, p2)]print()transition(p1, p1.run, RUNNING)transition(p2, p2.wait, WAITING) [state_info(p)for p in (p1, p2)]print()transition(p2, p2.run, RUNNING) [state_info(p)for p in (p1, p2)]print() [transition(p, p.block, BLOCKED)for p in (p1, p2)] [state_info(p)for p in (p1, p2)]print() [transition(p, p.terminate, TERMINATED)for p in (p1, p2)] [state_info(p)for p in (p1, p2)]if__name__=='__main__':main()