asyncdeffactorial(name, number):#定义要并发运行的函数
f =1for i inrange(2, number +1):print(f"Task {name}: Compute factorial({i})...")await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")asyncdefmain():#定义主函数# Schedule three calls *concurrently*:await asyncio.gather(#并发运行
factorial("A",2),
factorial("B",3),
factorial("C",4),)
asyncio.run(main())
屏蔽取消操作
res =await shield(something())
等待超时
asyncdefeternity():# Sleep for one hourawait asyncio.sleep(3600)print('yay!')asyncdefmain():# Wait for at most 1 secondtry:await asyncio.wait_for(eternity(), timeout=1.0)except asyncio.TimeoutError:print('timeout!')
在线程中运行
defblocking_io():print(f"start blocking_io at {time.strftime('%X')}")# Note that time.sleep() can be replaced with any blocking# IO-bound operation, such as file operations.
time.sleep(1)print(f"blocking_io complete at {time.strftime('%X')}")asyncdefmain():print(f"started main at {time.strftime('%X')}")await asyncio.gather(
asyncio.to_thread(blocking_io),
asyncio.sleep(1))print(f"finished main at {time.strftime('%X')}")
asyncio.run(main())
来自其他线程的日程安排
# Create a coroutine
coro = asyncio.sleep(1, result=3)# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)# Wait for the result with an optional timeout argumentassert future.result(timeout)==3