1、 asynciopython
1.python3.4開始引入標準庫之中,內置對異步io的支持git
2.asyncio自己是一個消息循環github
3.步驟:web
(1)建立消息循環微信
(2)把協程導入併發
(3)關閉app
4.舉例:框架
import threading #引入異步io包 import asyncio #使用協程 @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()) #啓動消息循環 loop = asyncio.get_event_loop() #定義任務 tasks = [hello(),hello()] #asyncio使用wait等待task執行完畢 loop.run_until_complete(asyncio.wait(tasks)) #關閉消息循環 loop.close()
2、asyncio and await異步
1.爲了更好的表示異步ioasync
2.python3.5引入
3.讓協程代碼更加簡潔
4.使用上,能夠簡單的進行替換
(1)用async來替換@asyncio,coroutine
(2)用await來替換yield from
按照上面這個語法能夠來改寫前面的例子,運行結果是徹底一致的
3、aiohttp
1.asyncio實現單線程的併發io,在客戶端用處不大
2.在服務端能夠asyncio+coroutine配合,由於http是io操做
3.asyncio實現了tcp,udp,ssl等協議
4.aiohttp是基於asyncio實現的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()
3、current,futures
1. python3新增的庫
2.相似其它語言的線程池的概念
3.利用multiprocessing實現真正的並行計算(固然要求咱們的CPU是多核的)
4.核心原理:以子進程的形式,實現多個python解釋器
從而令python程序,能夠利用多核CPU來提高執行速度。因爲子進程於主解釋器相分離,因此他們的全局解釋器鎖也是相互獨立的,每一個子進程都能完整的使用一個CPU內核
5.concurrent.futures.Executor
(1)ThreadPoolExecutor
(2)ProcessPoolExecutor
(3)執行的時候須要自行選擇
(4)submit(fn,args,kwargs)
fn:異步執行的函數
args,kwargs參數
import time from concurrent.futures import ThreadPoolExecutor def return_future(msg): time.sleep(3) return msg #建立一個線程池 pool = ThreadPoolExecutor(max_workers = 2)#參數是2,表明裏面有兩個線程幹活 #往線程池裏面加入兩個task f1 = pool.submit(return_future,"hello") f2 = pool.submit(return_future,"world") time.sleep(1) #等待執行完畢 print(f1.done()) time.sleep(3) print(f2.done()) #結果 print(f1.result()) print(f2.result())
5、源碼
d28_1_asynchronization_examples.py
https://github.com/ruigege66/Python_learning/blob/master/d28_1_asynchronization_examples.py
2.CSDN:https://blog.csdn.net/weixin_44630050(心悅君兮君不知-睿)
3.博客園:https://www.cnblogs.com/ruigege0000/
4.歡迎關注微信公衆號:傅里葉變換,我的公衆號,僅用於學習交流,後臺回覆」禮包「,獲取大數據學習資料