python在協(xié)程中增加任務(wù)實(shí)例操作
1、添加一個(gè)任務(wù)
task2 = visit_url('http://another.com', 3) asynicio.run(task2)
2、這 2 個(gè)程序一共消耗 5s 左右的時(shí)間。并沒(méi)有發(fā)揮并發(fā)編程的優(yōu)勢(shì)
import asyncio import time async def visit_url(url, response_time): """訪問(wèn) url""" await asyncio.sleep(response_time) return f"訪問(wèn){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)
實(shí)例擴(kuò)展:
import asyncio from threading import Thread async def production_task(): i = 0 while True: # 將consumption這個(gè)協(xié)程每秒注冊(cè)一個(gè)到運(yùn)行在線程中的循環(huán),thread_loop每秒會(huì)獲得一個(gè)一直打印i的無(wú)限循環(huán)任務(wù) asyncio.run_coroutine_threadsafe(consumption(i), thread_loop) # 注意:run_coroutine_threadsafe 這個(gè)方法只能用在運(yùn)行在線程中的循環(huán)事件使用 await asyncio.sleep(1) # 必須加await i += 1 async def consumption(i): while True: print("我是第{}任務(wù)".format(i)) await asyncio.sleep(1) def start_loop(loop): # 運(yùn)行事件循環(huán), loop以參數(shù)的形式傳遞進(jìn)來(lái)運(yùn)行 asyncio.set_event_loop(loop) loop.run_forever() thread_loop = asyncio.new_event_loop() # 獲取一個(gè)事件循環(huán) run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) # 將次事件循環(huán)運(yùn)行在一個(gè)線程中,防止阻塞當(dāng)前主線程 run_loop_thread.start() # 運(yùn)行線程,同時(shí)協(xié)程事件循環(huán)也會(huì)運(yùn)行 advocate_loop = asyncio.get_event_loop() # 將生產(chǎn)任務(wù)的協(xié)程注冊(cè)到這個(gè)循環(huán)中 advocate_loop.run_until_complete(production_task()) # 運(yùn)行次循環(huán)
到此這篇關(guān)于python在協(xié)程中增加任務(wù)實(shí)例操作的文章就介紹到這了,更多相關(guān)python在協(xié)程中增加任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中樹(shù)與樹(shù)的表示知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家分享的是關(guān)于python中樹(shù)與樹(shù)的表示的相關(guān)知識(shí)點(diǎn),需要的讀者們學(xué)習(xí)下吧。2019-09-09python3 traceback模塊來(lái)追蹤和打印異常信息
本文主要介紹了python3 traceback模塊來(lái)追蹤和打印異常信息,這個(gè)模塊提供了許多函數(shù)來(lái)處理異常,并且能夠輸出異常的堆棧信息,感興趣的可以了解一下2024-02-02python 爬蟲(chóng)網(wǎng)頁(yè)登陸的簡(jiǎn)單實(shí)現(xiàn)
這篇文章主要介紹了python 爬蟲(chóng)網(wǎng)頁(yè)登陸的簡(jiǎn)單實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11Python實(shí)現(xiàn)導(dǎo)彈自動(dòng)追蹤代碼實(shí)例
這篇文章主要介紹了Python實(shí)現(xiàn)導(dǎo)彈自動(dòng)追蹤代碼實(shí)例,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-11-11Python中使用glob和rmtree刪除目錄子目錄及所有文件的例子
這篇文章主要介紹了python中使用glob和rmtree刪除目錄子目錄及所有文件的例子,需要的朋友可以參考下2014-11-11