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()

猜你喜欢

转载自blog.csdn.net/qq_33251995/article/details/85527498
今日推荐