how to get the list form dictionary's values

Marko Rauhamaa marko at pacujo.net
Sun Feb 21 10:16:05 EST 2016


Chris Angelico <rosuav at gmail.com>:

> On Mon, Feb 22, 2016 at 1:15 AM, Ho Yeung Lee <davidbenny2000 at gmail.com> wrote:
>> 0 ---> 2 --> 3--> 1 ---> 0
>>         ---> 4 /
>
> So after task 2 completes, tasks 3 and 4 both become available (and
> can run in parallel), but then task 1 must wait until both have
> finished before it runs? I'm not an asyncio expert, but this sounds
> like a fairly straight-forward dependency requirement. If you were to
> implement these as four separate threads, you would have threads 3 and
> 4 raise semaphores which thread 1 blocks on; I'm sure there'll be an
> equivalent in asyncio.
>
> [...]
>
> (Can an asyncio expert tell me how to tidy this code up, please? I'm
> sure this isn't the cleanest.)

Not an expert, but this does the trick:

========================================================================
#!/usr/bin/env python3

import asyncio

def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(t0())
    
async def t0():
    print("start t0")
    await t2()
    await asyncio.wait([ t3(), t4() ])
    await t1()
    print("finish t0")

async def t1():
    print("start t1")
    await asyncio.sleep(1)
    print("finish t1")

async def t2():
    print("start t2")
    await asyncio.sleep(1)
    print("finish t2")

async def t3():
    print("start t3")
    await asyncio.sleep(1)
    print("finish t3")

async def t4():
    print("start t4")
    await asyncio.sleep(1)
    print("finish t4")

if __name__ == '__main__':
    main()
========================================================================


Marko



More information about the Python-list mailing list