关于python中使用协程asyncio的四个案例
本次四个案例包括
import asyncio
import time
Example 1: sample
async def task_print():
print('Hello...')
await asyncio.sleep(1)
print('...World!')
Example 2: async_taskgroups
async def delay_print(time:float,context:str):
await asyncio.sleep(time)
print(context)
async def delay_return(time:float,context:str):
await asyncio.sleep(time)
return context
asyncio.TaskGroup 在Python 3.10版本引入,在本次案例中替代asyncio.gather()
async def async_taskgroups():
async with asyncio.TaskGroup() as tg:
task1 = tg.create_task(delay_return(1,"sign1"))
task2 = tg.create_task(delay_return(0.5,"sign2"))
print(f"result1:{task1.result()},result2:{task2.result()}")
Example 3:run in thread
def blocking_io():
print(f"start blocking_io at {time.strftime('%X')}")
# 请注意 time.sleep() 可被替换为任意一种
# 阻塞式 IO 密集型操作,例如文件操作。
time.sleep(1)
print(f"blocking_io complete at {time.strftime('%X')}")
async def run_in_thread():
await asyncio.gather(
asyncio.to_thread(blocking_io),
asyncio.sleep(3))
Example 4: run coroutine thread
loop = asyncio.get_event_loop_policy().new_event_loop()
async def run_coroutine_thread():
await asyncio.sleep(1,result=3)
if name == "main":
print(f"started at {time.strftime('%X')}")
# asyncio.run(task_print())
# asyncio.run(async_taskgroups())
# asyncio.run(run_in_thread())
# future = asyncio.run_coroutine_threadsafe(run_coroutine_thread(),loop)
print(f"finished at {time.strftime('%X')}")
浙公网安备 33010602011771号