1. 程式人生 > 程式設計 >Python 非同步協程函式原理及例項詳解

Python 非同步協程函式原理及例項詳解

這篇文章主要介紹了Python 非同步協程函式原理及例項詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

一、 asyncio

1.python3.4開始引入標準庫之中,內建對非同步io的支援

2.asyncio本身是一個訊息迴圈

3.步驟:

(1)建立訊息迴圈

(2)把協程匯入

(3)關閉

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()

二、asyncio and await

1.為了更好的表示非同步io

2.python3.5引入

3.讓協程程式碼更加簡潔

4.使用上,可以簡單的進行替換

(1)用async來替換@asyncio,coroutine

(2)用await來替換yield from

按照上面這個語法可以來改寫前面的例子,執行結果是完全一致的

三、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()

四、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())

原始碼

d28_1_asynchronization_examples.py

https://github.com/ruigege66/Python_learning/blob/master/d28_1_asynchronization_examples.py

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。