(original) (raw)
import asyncio async def self_await_func1(n): """ This function takes in a parameter n. If n is <= 0 it prints and returns. Otherwise, it awaits itself, passing in n-1 as the parameter. """ if n <= 0: print("self_await_func1 finished") return print("self_await_func1 has n value of {}".format(n)) await self_await_func1(n-1) return async def self_await_func2(m): """ This function takes in a parameter m. If m is <= 0 it prints and returns. Otherwise, it awaits itself, passing in m-1 as the parameter. """ if m <= 0: print("self_await_func2 finished") return print("self_await_func2 has m value of {}".format(m)) await self_await_func2(m-1) return async def self_await_sleep_func1(n): """ This function takes in a parameter n. If n is <= 0 it prints and returns. Otherwise, it first awaits a 0 second asyncio sleep, and then awaits itself, passing in n-1 as the parameter. """ if n <= 0: print("self_await_sleep_func1 finished") return print("self_await_sleep_func1 has n value of {}".format(n)) await asyncio.sleep(0) await self_await_sleep_func1(n-1) return async def self_await_sleep_func2(m): """ This function takes in a parameter n. If m is <= 0 it prints and returns. Otherwise, it first awaits a 0 second asyncio sleep, and then awaits itself, passing in m-1 as the parameter. """ if m == 0: print("self_await_sleep_func2 finished") return print("self_await_sleep_func2 has m value of {}".format(m)) await asyncio.sleep(0) await self_await_sleep_func2(m-1) return loop = asyncio.get_event_loop() self_awaiting_funcs = asyncio.gather(self_await_func1(5), self_await_func2(5)) self_awaiting_sleeping_funcs = asyncio.gather(self_await_sleep_func1(5), self_await_sleep_func2(5)) loop.run_until_complete(self_awaiting_funcs) """the above line will always print the following: self_await_func1 has n value of 5 self_await_func1 has n value of 4 self_await_func1 has n value of 3 self_await_func1 has n value of 2 self_await_func1 has n value of 1 self_await_func1 finished self_await_func2 has m value of 5 self_await_func2 has m value of 4 self_await_func2 has m value of 3 self_await_func2 has m value of 2 self_await_func2 has m value of 1 self_await_func2 finished """ loop.run_until_complete(self_awaiting_sleeping_funcs) """the above line will always print the following: self_await_sleep_func1 has n value of 5 self_await_sleep_func2 has m value of 5 self_await_sleep_func1 has n value of 4 self_await_sleep_func2 has m value of 4 self_await_sleep_func1 has n value of 3 self_await_sleep_func2 has m value of 3 self_await_sleep_func1 has n value of 2 self_await_sleep_func2 has m value of 2 self_await_sleep_func1 has n value of 1 self_await_sleep_func2 has m value of 1 self_await_sleep_func1 finished self_await_sleep_func2 finished """