- 異步IO
異步IO是指當(dāng)代碼執(zhí)行到一個(gè)耗時(shí)IO操作時(shí)乏矾,它只發(fā)出IO指令,然后就去執(zhí)行其他的代碼润匙,并不等待IO的執(zhí)行結(jié)果诗眨。當(dāng)一段時(shí)間后,IO操作返回結(jié)果時(shí)再通知CPU進(jìn)行處理孕讳。
異步IO模型需要一個(gè)消息循環(huán)匠楚,在消息循環(huán)中,主線程不斷地重復(fù)“讀取消息-處理消息”的過(guò)程:
loop = get_event_loop()
while True:
event = loop.get_event()
process_event(event)
- asyncio
asyncio是python3.4版本引入的標(biāo)準(zhǔn)庫(kù)厂财,直接內(nèi)置了對(duì)異步io的支持芋簿,它的編程模型就是一個(gè)消息循環(huán)。從asyncio模塊中直接獲取一個(gè)EventLoop的引用璃饱,然后把需要執(zhí)行的協(xié)程扔到Eventloop中執(zhí)行与斤,就實(shí)現(xiàn)了異步IO。
實(shí)例:
用asyncio的一部網(wǎng)絡(luò)來(lái)獲取sina荚恶、sohu和163的網(wǎng)站首頁(yè):
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
yield from writer.drain()
while True:
line = yield from reader.readline()
#yield from asyncio.sleep(2)
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
# Ignore the body, close the socket
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
執(zhí)行結(jié)果如下:
wget www.sina.com.cn...
wget www.163.com...
wget www.sohu.com...
www.sina.com.cn
www.sina.com.cn header > HTTP/1.1 200 OK
www.sina.com.cn header > Server: nginx
www.sina.com.cn header > Date: Mon, 19 Sep 2016 03:03:30 GMT
www.sina.com.cn header > Content-Type: text/html
www.sina.com.cn header > Last-Modified: Mon, 19 Sep 2016 03:03:13 GMT
www.sina.com.cn header > Vary: Accept-Encoding
www.sina.com.cn header > Expires: Mon, 19 Sep 2016 03:04:30 GMT
www.sina.com.cn header > Cache-Control: max-age=60
www.sina.com.cn header > X-Powered-By: schi_v1.02
www.sina.com.cn header > Age: 52
www.sina.com.cn header > Content-Length: 593409
www.sina.com.cn header > X-Cache: HIT from localhost
www.sina.com.cn header > Connection: close
www.163.com
www.163.com header > HTTP/1.1 200 OK
www.163.com header > Expires: Mon, 19 Sep 2016 03:05:44 GMT
www.163.com header > Date: Mon, 19 Sep 2016 03:04:24 GMT
www.163.com header > Server: nginx
www.163.com header > Content-Type: text/html; charset=GBK
www.163.com header > Vary: Accept-Encoding,User-Agent,Accept
www.163.com header > Cache-Control: max-age=80
www.163.com header > X-Via: 1.1 czdx87:4 (Cdn Cache Server V2.0), 1.1 jifang134:10 (Cdn Cache Server V2.0)
www.163.com header > Connection: close
www.sohu.com
www.sohu.com header > HTTP/1.1 200 OK
www.sohu.com header > Content-Type: text/html
www.sohu.com header > Content-Length: 92145
www.sohu.com header > Connection: close
www.sohu.com header > Date: Mon, 19 Sep 2016 03:02:52 GMT
www.sohu.com header > Server: SWS
www.sohu.com header > Vary: Accept-Encoding
www.sohu.com header > Cache-Control: no-transform, max-age=120
www.sohu.com header > Expires: Mon, 19 Sep 2016 03:04:52 GMT
www.sohu.com header > Last-Modified: Mon, 19 Sep 2016 03:02:45 GMT
www.sohu.com header > Content-Encoding: gzip
www.sohu.com header > X-RS: 17799606.26974656.25737794
www.sohu.com header > FSS-Cache: HIT from 5397379.8739725.6791606
www.sohu.com header > FSS-Proxy: Powered by 3496806.4938608.4891004
在上述執(zhí)行結(jié)果中撩穿,按照正常的異步IO的邏輯,打印出header的host不應(yīng)該連續(xù)谒撼,但實(shí)際上食寡,出現(xiàn)這種結(jié)果的原因是因?yàn)閘ine = yield from reader.readline() 的執(zhí)行時(shí)間非常短,還沒(méi)有等到線程去執(zhí)行其他任務(wù)的時(shí)候就已經(jīng)執(zhí)行完畢廓潜,所以就出現(xiàn)了連續(xù)打印的結(jié)果抵皱。(個(gè)人理解)
比如將上述注釋掉的yield from asyncio.sleep(2)還原回來(lái),則執(zhí)行結(jié)果就變成了如下結(jié)果:
wget www.sina.com.cn...
wget www.163.com...
wget www.sohu.com...
www.sina.com.cn
www.163.com
www.sohu.com
www.sina.com.cn header > HTTP/1.1 200 OK
www.sohu.com header > HTTP/1.1 200 OK
www.sina.com.cn header > Server: nginx
www.sohu.com header > Content-Type: text/html
www.163.com header > HTTP/1.1 200 OK
www.sina.com.cn header > Date: Mon, 19 Sep 2016 03:07:54 GMT
www.sohu.com header > Content-Length: 92072
www.163.com header > Date: Mon, 19 Sep 2016 03:08:56 GMT
www.sina.com.cn header > Content-Type: text/html
www.sohu.com header > Connection: close
www.163.com header > Server: openresty
www.sina.com.cn header > Last-Modified: Mon, 19 Sep 2016 03:06:45 GMT
www.sohu.com header > Date: Mon, 19 Sep 2016 03:05:22 GMT
www.163.com header > Content-Type: text/html; charset=GBK
www.sina.com.cn header > Vary: Accept-Encoding
拓展
yield
yield的功能類(lèi)似于return茉帅,加上yield的函數(shù)便不再是普通的函數(shù)叨叙,而變成了生成器。每當(dāng)代碼執(zhí)行到了yield堪澎,代碼就會(huì)中斷執(zhí)行擂错,下次再繼續(xù)從中斷處繼續(xù)執(zhí)行。具體參考如下:
yield的作用yield和yield from
yield from會(huì)把內(nèi)嵌的generator輸出當(dāng)做當(dāng)前generator輸出的一部分樱蛤。
def g(x):
... yield from range(x, 0, -1)
... yield from range(x)
...
list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
也就是說(shuō)yield from是可以將generator串聯(lián)的钮呀。