日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(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