溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用python怎么實現在協程中增加任務

發(fā)布時間:2021-03-01 15:09:19 來源:億速云 閱讀:176 作者:戴恩恩 欄目:開發(fā)技術

這篇文章主要介紹了使用python怎么實現在協程中增加任務,此處通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考價值,需要的朋友可以參考下:

python是什么意思

Python是一種跨平臺的、具有解釋性、編譯性、互動性和面向對象的腳本語言,其最初的設計是用于編寫自動化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨立的項目和大型項目。

1、添加一個任務

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}, 已得到返回結果"

async def run_task():
  """收集子任務"""
  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 個子任務,當出現 await 的時候,程序會在這 2 個子任務之間進行調度。

async def run_task():
  """收集子任務"""
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asynicio.gather(task1, task2)

實例擴展:

import asyncio
from threading import Thread
 
 
async def production_task():
  i = 0
  while True:
    # 將consumption這個協程每秒注冊一個到運行在線程中的循環(huán),thread_loop每秒會獲得一個一直打印i的無限循環(huán)任務
    asyncio.run_coroutine_threadsafe(consumption(i),
                     thread_loop) # 注意:run_coroutine_threadsafe 這個方法只能用在運行在線程中的循環(huán)事件使用
    await asyncio.sleep(1) # 必須加await
    i += 1
 
 
async def consumption(i):
  while True:
    print("我是第{}任務".format(i))
    await asyncio.sleep(1)
 
 
def start_loop(loop):
  # 運行事件循環(huán), loop以參數的形式傳遞進來運行
  asyncio.set_event_loop(loop)
  loop.run_forever()
 
 
thread_loop = asyncio.new_event_loop() # 獲取一個事件循環(huán)
run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) # 將次事件循環(huán)運行在一個線程中,防止阻塞當前主線程
run_loop_thread.start() # 運行線程,同時協程事件循環(huán)也會運行
 
advocate_loop = asyncio.get_event_loop() # 將生產任務的協程注冊到這個循環(huán)中
advocate_loop.run_until_complete(production_task()) # 運行次循環(huán)

到此這篇關于使用python怎么實現在協程中增加任務的文章就介紹到這了,更多相關使用python怎么實現在協程中增加任務的內容請搜索億速云以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持億速云!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI