python在協(xié)程中增加任務(wù)實例操作
1、添加一個任務(wù)
task2 = visit_url(’http://another.com’, 3)asynicio.run(task2)
2、這 2 個程序一共消耗 5s 左右的時間。并沒有發(fā)揮并發(fā)編程的優(yōu)勢
import asyncioimport timeasync 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ù),當出現(xiàn) await 的時候,程序會在這 2 個子任務(wù)之間進行調(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)
實例擴展:
import asynciofrom threading import Thread async def production_task(): i = 0 while True: # 將consumption這個協(xié)程每秒注冊一個到運行在線程中的循環(huán),thread_loop每秒會獲得一個一直打印i的無限循環(huán)任務(wù) 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('我是第{}任務(wù)'.format(i)) await asyncio.sleep(1) def start_loop(loop): # 運行事件循環(huán), loop以參數(shù)的形式傳遞進來運行 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() # 運行線程,同時協(xié)程事件循環(huán)也會運行 advocate_loop = asyncio.get_event_loop() # 將生產(chǎn)任務(wù)的協(xié)程注冊到這個循環(huán)中advocate_loop.run_until_complete(production_task()) # 運行次循環(huán)
到此這篇關(guān)于python在協(xié)程中增加任務(wù)實例操作的文章就介紹到這了,更多相關(guān)python在協(xié)程中增加任務(wù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. js select支持手動輸入功能實現(xiàn)代碼2. 如何在PHP中讀寫文件3. java加載屬性配置properties文件的方法4. PHP正則表達式函數(shù)preg_replace用法實例分析5. 什么是Python變量作用域6. 《Java程序員修煉之道》作者Ben Evans:保守的設(shè)計思想是Java的最大優(yōu)勢7. CSS3中Transition屬性詳解以及示例分享8. php redis setnx分布式鎖簡單原理解析9. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼10. vue使用moment如何將時間戳轉(zhuǎn)為標準日期時間格式
