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.

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(asyncio.gather(add_two_V(1,2),add_two_V(3,4)))
print(result)
loop.close()


版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论