新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python在協(xié)程中增加任務(wù)
1、添加一個任務(wù)

task2 = visit_url('http://another.com', 3)
asynicio.run(task2)2、這 2 個程序一共消耗 5s 左右的時間。并沒有發(fā)揮并發(fā)編程的優(yōu)勢
import asyncio
import time
async def visit_url(url, response_time):
"""訪問 url"""
await asyncio.sleep(response_time)
return f"訪問{url}, 已得到返回結(jié)果"
async def run_task():
"""收集子任務(wù)"""
task = visit_url('http://wangzhen.com', 2)
task_2 = visit_url('http://another', 3)
await asyncio.run(task)
await asyncio.run(task_2)
asyncio.run(run_task())
print(f"消耗時間:{time.perf_counter() - start_time}")3、如果是并發(fā)編程,這個程序只需要消耗 3s,也就是task2的等待時間。要想使用并發(fā)編程形式,需要把上面的代碼改一下。asyncio.gather 會創(chuàng)建 2 個子任務(wù),當(dāng)出現(xiàn) await 的時候,程序會在這 2 個子任務(wù)之間進(jìn)行調(diào)度。
async def run_task():
"""收集子任務(wù)"""
task = visit_url('http://wangzhen.com', 2)
task_2 = visit_url('http://another', 3)
await asynicio.gather(task1, task2)以上就是python在協(xié)程中增加任務(wù)的方法,希望能對大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程
分享題目:創(chuàng)新互聯(lián)Python教程:python在協(xié)程中增加任務(wù)
網(wǎng)址分享:http://www.dlmjj.cn/article/cocsssj.html


咨詢
建站咨詢
