chzzz's Blog

The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.--Stephen William Hawking

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


发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

© 版权所有:沈阳市和平区赛博空间咨询部|辽ICP备18005891号
Powered by Z-BlogPHP & Yiwuku.com