Python 異步協(xié)程函數(shù)原理及實例詳解
這篇文章主要介紹了Python 異步協(xié)程函數(shù)原理及實例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
一、 asyncio
1.python3.4開始引入標(biāo)準(zhǔn)庫之中,內(nèi)置對異步io的支持
2.asyncio本身是一個消息循環(huán)
3.步驟:
(1)創(chuàng)建消息循環(huán)
(2)把協(xié)程導(dǎo)入
(3)關(guān)閉
4.舉例:
import threading # 引入異步io包 import asyncio # 使用協(xié)程 @ asyncio.coroutine def hello(): print("Hello World!(%s)" % threading.current_thread()) print("Start......(%s)" % threading.current_thread()) yield from asyncio.sleep(5) print("Done.....(%s)" % threading.current_thread()) print("Hello again!(%s)" % threading.current_thread()) # 啟動消息循環(huán) loop = asyncio.get_event_loop() # 定義任務(wù) tasks = [hello(), hello()] # asyncio使用wait等待task執(zhí)行完畢 loop.run_until_complete(asyncio.wait( tasks)) # 關(guān)閉消息循環(huán) loop.close()
二、asyncio and await
1.為了更好的表示異步io
2.python3.5引入
3.讓協(xié)程代碼更加簡潔
4.使用上,可以簡單的進行替換
(1)用async來替換@asyncio,coroutine
(2)用await來替換yield from
按照上面這個語法可以來改寫前面的例子,運行結(jié)果是完全一致的
三、aiohttp
1.asyncio實現(xiàn)單線程的并發(fā)io,在客戶端用處不大
2.在服務(wù)端可以asyncio+coroutine配合,因為http是io操作
3.asyncio實現(xiàn)了tcp,udp,ssl等協(xié)議
4.aiohttp是基于asyncio實現(xiàn)的http框架
5.例子:
import asyncio from aiohttp import web async def index(request): await asyncio.sleep(0.5) return web.Response(body = b "<h1>Index</h1>") async def hello(request): await asyncio.sleep(0.5) text = "<h1>hello,%s!</h1>" % request.match_info[ "name"] return web.Response(body = text.encode( "utf-8")) async def init(loop): app = web.Application(loop = loop) app.router.add_route("GET", "/", index) app.router.add_route("GET", "/hellp/{name}", hello) srv = await loop.create_server(app.make_handler(), "127.0.0.1", 8000) print( "Server started at http://127.0.0.1:8000..." ) return srv loop = asyncio.get_event_loop() loop.run_until_complete(init(loop)) loop.run_forever()
四、current,futures
1. python3新增的庫
2.類似其它語言的線程池的概念
3.利用multiprocessing實現(xiàn)真正的并行計算(當(dāng)然要求我們的CPU是多核的)
4.核心原理:以子進程的形式,實現(xiàn)多個python解釋器
從而令python程序,可以利用多核CPU來提升執(zhí)行速度。由于子進程于主解釋器相分離,所以他們的全局解釋器鎖也是相互獨立的,每個子進程都能完整的使用一個CPU內(nèi)核
5.concurrent.futures.Executor
(1)ThreadPoolExecutor
(2)ProcessPoolExecutor
(3)執(zhí)行的時候需要自行選擇
(4)submit(fn,args,kwargs)
fn:異步執(zhí)行的函數(shù)
args,kwargs參數(shù)
import time from concurrent.futures import ThreadPoolExecutor def return_future(msg): time.sleep(3) return msg # 創(chuàng)建一個線程池 pool = ThreadPoolExecutor(max_workers = 2)# 參數(shù)是2, 代表里面有兩個線程干活 # 往線程池里面加入兩個task f1 = pool.submit(return_future, "hello") f2 = pool.submit(return_future, "world") time.sleep(1) # 等待執(zhí)行完畢 print(f1.done()) time.sleep(3) print(f2.done()) # 結(jié)果 print(f1.result()) print(f2.result())
源碼
d28_1_asynchronization_examples.py
https://github.com/ruigege66/Python_learning/blob/master/d28_1_asynchronization_examples.py
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pytorch Dataset,DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例
這篇文章主要介紹了pytorch Dataset, DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python調(diào)用高德API實現(xiàn)批量地址轉(zhuǎn)經(jīng)緯度并寫入表格的功能
這篇文章主要介紹了Python調(diào)用高德API實現(xiàn)批量地址轉(zhuǎn)經(jīng)緯度并寫入表格的功能,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01python網(wǎng)絡(luò)編程之讀取網(wǎng)站根目錄實例
這篇文章主要介紹了python網(wǎng)絡(luò)編程之讀取網(wǎng)站根目錄實例,以quux.org站根目錄為例進行了實例分析,代碼簡單易懂,需要的朋友可以參考下2014-09-09Python中基本數(shù)據(jù)類型和常用語法歸納分享
這篇文章主要為大家整理記錄了Python中基本數(shù)據(jù)類型和常用語法的使用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04python 中關(guān)于pycharm選擇運行環(huán)境的問題
這篇文章主要介紹了python 中關(guān)于pycharm選擇運行環(huán)境的相關(guān)知識,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10