Python 異步協(xié)程函數(shù)原理及實(shí)例詳解
這篇文章主要介紹了Python 異步協(xié)程函數(shù)原理及實(shí)例詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
一、 asyncio
1.python3.4開始引入標(biāo)準(zhǔn)庫之中,內(nèi)置對(duì)異步io的支持
2.asyncio本身是一個(gè)消息循環(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()) # 啟動(dòng)消息循環(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é)程代碼更加簡(jiǎn)潔
4.使用上,可以簡(jiǎn)單的進(jìn)行替換
(1)用async來替換@asyncio,coroutine
(2)用await來替換yield from
按照上面這個(gè)語法可以來改寫前面的例子,運(yùn)行結(jié)果是完全一致的
三、aiohttp
1.asyncio實(shí)現(xiàn)單線程的并發(fā)io,在客戶端用處不大
2.在服務(wù)端可以asyncio+coroutine配合,因?yàn)閔ttp是io操作
3.asyncio實(shí)現(xiàn)了tcp,udp,ssl等協(xié)議
4.aiohttp是基于asyncio實(shí)現(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實(shí)現(xiàn)真正的并行計(jì)算(當(dāng)然要求我們的CPU是多核的)
4.核心原理:以子進(jìn)程的形式,實(shí)現(xiàn)多個(gè)python解釋器
從而令python程序,可以利用多核CPU來提升執(zhí)行速度。由于子進(jìn)程于主解釋器相分離,所以他們的全局解釋器鎖也是相互獨(dú)立的,每個(gè)子進(jìn)程都能完整的使用一個(gè)CPU內(nèi)核
5.concurrent.futures.Executor
(1)ThreadPoolExecutor
(2)ProcessPoolExecutor
(3)執(zhí)行的時(shí)候需要自行選擇
(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)建一個(gè)線程池 pool = ThreadPoolExecutor(max_workers = 2)# 參數(shù)是2, 代表里面有兩個(gè)線程干活 # 往線程池里面加入兩個(gè)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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pytorch Dataset,DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例
這篇文章主要介紹了pytorch Dataset, DataLoader產(chǎn)生自定義的訓(xùn)練數(shù)據(jù)案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python調(diào)用高德API實(shí)現(xiàn)批量地址轉(zhuǎn)經(jīng)緯度并寫入表格的功能
這篇文章主要介紹了Python調(diào)用高德API實(shí)現(xiàn)批量地址轉(zhuǎn)經(jīng)緯度并寫入表格的功能,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Python/JS實(shí)現(xiàn)常見加密算法的示例代碼
這篇文章主要為大家詳細(xì)介紹了常見的一些JS加密,并記錄了JS和Python的實(shí)現(xiàn)方式,主要有base64編碼偽加密、MD5、SHAI等,需要的可以參考一下2022-11-11python網(wǎng)絡(luò)編程之讀取網(wǎng)站根目錄實(shí)例
這篇文章主要介紹了python網(wǎng)絡(luò)編程之讀取網(wǎng)站根目錄實(shí)例,以quux.org站根目錄為例進(jìn)行了實(shí)例分析,代碼簡(jiǎn)單易懂,需要的朋友可以參考下2014-09-09Python中基本數(shù)據(jù)類型和常用語法歸納分享
這篇文章主要為大家整理記錄了Python中基本數(shù)據(jù)類型和常用語法的使用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-04-04python 中關(guān)于pycharm選擇運(yùn)行環(huán)境的問題
這篇文章主要介紹了python 中關(guān)于pycharm選擇運(yùn)行環(huán)境的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10Python中串口通信庫pyserial基礎(chǔ)知識(shí)
Python的pyserial庫是一個(gè)用于通過串口進(jìn)行通信的庫,下面這篇文章主要給大家介紹了關(guān)于Python中串口通信庫pyserial基礎(chǔ)知識(shí)的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08