mardi 21 avril 2020

In a Python asyncio state machine, how do I prevent states behind destroyed that have a pending task

I have a utility class that schedules a job to be executed in timeout seconds:

class AsyncTimer:
    def __init__(self, timeout, callback):
        self._timeout = timeout
        self._callback = callback
        self._task = asyncio.ensure_future(self._job())

    async def _job(self):
        await asyncio.sleep(self._timeout)
        await self._callback()

I also have a state machine that is similar to the following:

class IState(metaclass=abc.ABCMeta):
    def __init__(self, machine):
        self._machine = machine

# The OnState can only transition into the TurningOffState, etc...
class OnState(IState):
    def __init__(self, machine):
        super().__init__(machine)
        print("Turned on!")     
    def turnOff(self):
        self.__machine.currentState = TurningOffState(self._machine)

class OffState(IState):
    def __init__(self, machine):
        super().__init__(machine)
        print("Turned off!")     
    def turnOn(self):
        self.__machine.currentState = TurningOnState(self._machine)

# Transition state that has no state transitions. automaticly transitions to `OnState` after 2 secconds
class TurningOnState(IState):
    async def _callback(self):
        self._machine.currentState = OnState(self._machine)
    def __init__(self, machine):
        super().__init__(machine)
        print("Turning on!")
        self.__timer = AsyncTimer(2, self._callback)

I have an object that contains the currently active state:

class FSM:
    def __init__(self):
        self.currentState = OffState(self)
    def __del__(self):
        print("destroying FSM")

My main loop looks like this:

async def main():        
    fsm = FSM()
    fsm.currentState.turnOn()
    # fsm gets destroyed here, along with currently contained state which may have a pending task. How do I fix this?


loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

This outputs:

Turned Off!
Turning On!
destroying FSM
Task was destroyed but it is pending!
task: <Task pending coro=<AsyncTimer._job() done, defined at pythreadtest.py:11> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x7f0c1d891258>()]>>

I'm pretty sure the problem is that the FSM gets destroyed after the request to be turned on, along with currently contained state which may have a pending task.

How could I fix this? Is there something I could put in the destructor to await the completion off all pending tasks? How could I do this? Are there any other problems with my design?

Thanks

edit

I tried adding a sleep after the transition request, but I still get the same error

fsm = DoorFSM()
fsm.currentState.openDoor()
time.sleep(3)
#Stll get same output / error...

Aucun commentaire:

Enregistrer un commentaire