国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python在協程中增加任務實例操作

瀏覽:2日期:2022-06-26 18:44:23

1、添加一個任務

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

2、這 2 個程序一共消耗 5s 左右的時間。并沒有發揮并發編程的優勢

import asyncioimport timeasync 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、如果是并發編程,這個程序只需要消耗 3s,也就是task2的等待時間。

要想使用并發編程形式,需要把上面的代碼改一下。asyncio.gather 會創建 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 asynciofrom threading import Thread async def production_task(): i = 0 while True: # 將consumption這個協程每秒注冊一個到運行在線程中的循環,thread_loop每秒會獲得一個一直打印i的無限循環任務 asyncio.run_coroutine_threadsafe(consumption(i), thread_loop) # 注意:run_coroutine_threadsafe 這個方法只能用在運行在線程中的循環事件使用 await asyncio.sleep(1) # 必須加await i += 1 async def consumption(i): while True: print('我是第{}任務'.format(i)) await asyncio.sleep(1) def start_loop(loop): # 運行事件循環, loop以參數的形式傳遞進來運行 asyncio.set_event_loop(loop) loop.run_forever() thread_loop = asyncio.new_event_loop() # 獲取一個事件循環run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) # 將次事件循環運行在一個線程中,防止阻塞當前主線程run_loop_thread.start() # 運行線程,同時協程事件循環也會運行 advocate_loop = asyncio.get_event_loop() # 將生產任務的協程注冊到這個循環中advocate_loop.run_until_complete(production_task()) # 運行次循環

到此這篇關于python在協程中增加任務實例操作的文章就介紹到這了,更多相關python在協程中增加任務內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 林芝县| 涞源县| 灵台县| 当涂县| 班戈县| 沙洋县| 永清县| 涟源市| 玛沁县| 曲麻莱县| 石门县| 云龙县| 法库县| 连平县| 黔东| 大方县| 韩城市| 江西省| 肃宁县| 卓尼县| 镇坪县| 余江县| 柘荣县| 上思县| 万州区| 隆德县| 榆社县| 城口县| 黑水县| 格尔木市| 枣阳市| 桑日县| 马尔康县| 邯郸市| 修水县| 五河县| 新昌县| 革吉县| 大竹县| 闻喜县| 淮南市|