1. 程式人生 > >full-speed-python習題解答(九)--非同步程式設計(Asynchronous programming)

full-speed-python習題解答(九)--非同步程式設計(Asynchronous programming)

 

Exercises with asyncio
1. Implement an asynchronous coroutine function to add two variables and sleep for
the duration of the sum. Use the asyncio loop to call the function with two numbers.

import asyncio
async def add_two_V(a,b):
    print(f"add {a} and {b}")
    await asyncio.sleep(1)
    print("End add",a,b)
    return a+b

loop = asyncio.get_event_loop()
result = loop.run_until_complete(add_two_V(1,2))
print(result)
loop.close()


2. Change the previous program to schedule the execution of two calls to the sum
function.
 

async def add_two_V(a,b):
    print(f"add {a} and {b}")
    await asyncio.sleep(1)
    print("End add",a,b)
    return a+b

loop = asyncio.get_event_loop()
result = loop.run_until_complete(asyncio.gather(add_two_V(1,2),add_two_V(3,4)))
print(result)
loop.close()