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.使用上,可以簡單的進(jìn)行替換
(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.核心原理:以子進(jìn)程的形式,實現(xiàn)多個python解釋器
從而令python程序,可以利用多核CPU來提升執(zhí)行速度。由于子進(jìn)程于主解釋器相分離,所以他們的全局解釋器鎖也是相互獨立的,每個子進(jìn)程都能完整的使用一個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)文章
python Tkinter版學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python Tkinter版學(xué)生管理系統(tǒng),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02
Python實現(xiàn)捕獲異常發(fā)生的文件和具體行數(shù)
這篇文章主要介紹了Python實現(xiàn)捕獲異常發(fā)生的文件和具體行數(shù)。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python代碼調(diào)用執(zhí)行shell踩坑解決
這篇文章主要為大家介紹了Python代碼調(diào)用執(zhí)行shell,踩過的坑解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
使用Python3實現(xiàn)判斷函數(shù)的圈復(fù)雜度
編寫函數(shù)最重要的原則就是:別寫太復(fù)雜的函數(shù),那什么樣的函數(shù)才能算是過于復(fù)雜?一般會通過兩個標(biāo)準(zhǔn)來判斷,長度和圈復(fù)雜度,下面我們就來看看如何使用Python判斷函數(shù)的圈復(fù)雜度吧2024-04-04
Python Numpy學(xué)習(xí)之索引及切片的使用方法
數(shù)組中的元素可以通過索引以及切片的手段進(jìn)行訪問或者修改,和列表的切片操作一樣。本文將詳細(xì)為大家介紹一下Python中的科學(xué)計算庫-Numpy的索引及切片的使用方法2022-01-01
Python如何利用Har文件進(jìn)行遍歷指定字典替換提交的數(shù)據(jù)詳解
這篇文章主要給大家介紹了關(guān)于Python如何利用Har文件進(jìn)行遍歷指定字典替換提交的數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Numpy中stack(),hstack(),vstack()函數(shù)用法介紹及實例
這篇文章主要介紹了Numpy中stack(),hstack(),vstack()函數(shù)用法介紹及實例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01

