Equivalent to asyncio.gather()

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
cefn
Posts: 230
Joined: Tue Aug 09, 2016 10:58 am

Re: Equivalent to asyncio.gather()

Post by cefn » Sat Jan 20, 2018 11:10 am

That's really helpful, @pythoncoder.

It helps me understand how new functionality can be layered on your library too, for example providing __iter__ implementation to imply an 'awaitable' signature, use of coro functions (factories) and partial application by passing the coro functions with their arguments into a wrapping class (presumably so that the only reference to the actual coro is 'private' and hence any await invocations are managed properly by the library). Lots to learn from that, thanks.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Task cancellation

Post by pythoncoder » Sat Jan 20, 2018 6:00 pm

You might be interested in my approach to task cancellation too. The aim was to enable a coro to pause until a set of tasks had actually completed cancellation and to provide a means of checking the running status of individual tasks. Given the latency which can occur between issuing the pending exception and the actual termination of the task this feedback can be essential in firmware applications.

It took me a while to come up with a solution which is simple in code and easy to use. You can see some example code in asyn_demos.py and some more thorough tests in cantest.py. In essence a cancellable is declared as:

Code: Select all

@asyn.cancellable
async def print_nums(num):
    while True:
        print(num)
        num += 1
        await asyn.sleep(1)
run with

Code: Select all

    loop.create_task(asyn.Cancellable(print_nums, res)())
and cancelled with

Code: Select all

await asyn.Cancellable.cancel_all()
This pauses until all cancellable coros have actually terminated.

There are quite a few options available including organising Cancellable tasks into groups or naming individual Cancellable tasks, but its use can be as simple as above.
Peter Hinch
Index to my micropython libraries.

Post Reply