Python之asyncio
发布时间
阅读量:
阅读量
一、协程
协程作为一种实现并发编程的途径,相较于多线程方式,能够有效规避因上下文切换而引发的性能限制问题。
二、实现方式
自Python3.7版本起,asyncio这一工具包被正式引入,开发者可通过该工程包完成并发编程的实现。
import asyncio
from datetime import datetime
async def craw_task(task):
if not task:
raise Exception("task为空")
second = int(task.split("_")[-1])
await asyncio.sleep(second)
print("sleep {} s".format(second))
print("task:{} is done".format(task))
async def main(tasklist):
tasks= [asyncio.create_task(craw_task(task))for task in tasklist]
'''
for task in tasks:
await task
'''
await asyncio.g
全部评论 (0)
还没有任何评论哟~
