6

I am pretty new with async programming and python in general but I want to implement an asynchronous function inside a state machine. The requirements are as follows:

  1. The async task must be cancellable at any point in time
  2. The async task must not block the main thread of execution
  3. The async task must call a callback once it is done.

In order to achieve target 1 & 2, I have succesfully implemented my async routine to run inside an executor as stated here: asyncio: Is it possible to cancel a future been run by an Executor?. While debugging, I see that I also accomplish #2 because the original thread continues succesfully. However, I am having a hard time implementing the callback function. Please notice that this callback function must run on the original thread, since it will change the state of the object assigned to it. How can I accomplish this?

My code:

class Free(State):

    def write(self, manager):
        write_future = self.write_async(manager)
        self.set_write_future(write_future)         
        self.change_state(manager, busy_state)    

    def write_async(self, manager):
        event = threading.Event()
        write_future = asyncio.get_event_loop().run_in_executor(None, self.async_write, 10, event)
        write_future.add_done_callback(functools.partial(self.async_write_callback, manager))
        return event    

    def async_write(self, seconds_to_block, event):
        for i in range(seconds_to_block):
            if event.is_set():
                return
            print('writing {}/{}'.format(i, seconds_to_block))
            time.sleep(1)
        print('done writing {}'.format(seconds_to_block))

    def async_write_callback(self, manager):
        #never gets called
        self.terminate_future()
        self.change_state(manager, free_state)  
Community
  • 1
  • 1
luisgepeto
  • 763
  • 1
  • 11
  • 36

0 Answers0