日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

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

新聞中心

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

1、添加一個(gè)任務(wù)

task2 = visit_url('http://another.com', 3)
asynicio.run(task2)

2、這 2 個(gè)程序一共消耗 5s 左右的時(shí)間。并沒有發(fā)揮并發(fā)編程的優(yōu)勢(shì)

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"消耗時(shí)間:{time.perf_counter() - start_time}")

3、如果是并發(fā)編程,這個(gè)程序只需要消耗 3s,也就是task2的等待時(shí)間。要想使用并發(fā)編程形式,需要把上面的代碼改一下。asyncio.gather 會(huì)創(chuàng)建 2 個(gè)子任務(wù),當(dāng)出現(xiàn) await 的時(shí)候,程序會(huì)在這 2 個(gè)子任務(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ù)的方法,希望能對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)python教程


本文題目:創(chuàng)新互聯(lián)Python教程:python在協(xié)程中增加任務(wù)
當(dāng)前路徑:http://www.5511xx.com/article/cocsssj.html