On Mon, Feb 22, 2016 at 1:15 AM, Ho Yeung Lee <davidbenny2...@gmail.com> wrote: > Hi Chris, > > 0 ---> 2 --> 3--> 1 ---> 0 > ---> 4 / > > i am practicing task flow in this graph situation > > when current state is 2 , there are 3 and 4 to run parallel and wait list of > tasks finish before running to 1 , > > however i feel that my code has been wrong because 3 and 4 can not combine to > run task 1 , > > which is the correct way to combine to run task 1?
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. One way to do it would be something like this: import asyncio loop = asyncio.get_event_loop() async def starter(): print("Starting!") global t1, t2 t1 = asyncio.Task(dep1()) t2 = asyncio.Task(dep2()) print("Done!") await dependent() async def dep1(): print("Dependency 1") await asyncio.sleep(3) print("Dep 1 done.") async def dep2(): print("Dependency 2") await asyncio.sleep(2) print("Dep 2 done.") async def dependent(): await t1 await t2 print("Deps are done - dependent can run.") loop.run_until_complete(starter()) The dependent task simply waits for each of its dependencies in turn. It doesn't matter which one finishes first; it won't do its main work until both are done. And if your starter and dependent are logically connected, you can just have the 'await' lines in the middle of one tidy function. (Can an asyncio expert tell me how to tidy this code up, please? I'm sure this isn't the cleanest.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list