欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python中asyncio模塊的深入講解

 更新時(shí)間:2019年06月10日 08:40:37   作者:且聽(tīng)風(fēng)吟  
這篇文章主要給大家介紹了關(guān)于Python中asyncio模塊的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

1. 概述

Python中 asyncio 模塊內(nèi)置了對(duì)異步IO的支持,用于處理異步IO;是Python 3.4版本引入的標(biāo)準(zhǔn)庫(kù)。

asyncio 的編程模型就是一個(gè)消息循環(huán)。我們從 asyncio 塊中直接獲取一個(gè) EventLoop 的引用,然后把需要執(zhí)行的協(xié)程扔到 EventLoop 中執(zhí)行,就實(shí)現(xiàn)了異步IO。

2. 用asyncio實(shí)現(xiàn)Hello world

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019/1/9 11:23
# @Author : Arrow and Bullet
# @FileName: test.py
# @Software: PyCharm
# @Blog :https://blog.csdn.net/qq_41800366
import asyncio

@asyncio.coroutine
def hello():
 print("Hello world!")
 # 異步調(diào)用asyncio.sleep(2): 
 yield from asyncio.sleep(2)
 print("Hello again!")

# 獲取EventLoop:
loop = asyncio.get_event_loop()
# 執(zhí)行coroutine
loop.run_until_complete(hello())
loop.close()

@asyncio.coroutine 把一個(gè) generator 標(biāo)記為 coroutine 類型,然后,我們就把這個(gè) coroutine 扔到 EventLoop 中執(zhí)行。

hello() 會(huì)首先打印出Hello world!,然后,yield from語(yǔ)法可以讓我們方便地調(diào)用另一個(gè)generator。由于 asyncio.sleep() 也是一個(gè) coroutine,所以線程不會(huì)等待 asyncio.sleep() ,而是直接中斷并執(zhí)行下一個(gè)消息循環(huán)。當(dāng)asyncio.sleep()返回時(shí),線程就可以從yield from拿到返回值(此處是None),然后接著執(zhí)行下一行語(yǔ)句。

把a(bǔ)syncio.sleep(2)看成是一個(gè)耗時(shí)2秒的IO操作(比如讀取大文件),在此期間,主線程并未等待,而是去執(zhí)行 EventLoop 中其他可以執(zhí)行的 coroutine 了,因此可以實(shí)現(xiàn)并發(fā)執(zhí)行。

我們用task封裝兩個(gè)coroutine試試:

import threading
import asyncio


@asyncio.coroutine
def hello():
 print('Hello world! (%s)' % threading.currentThread())
 yield from asyncio.sleep(2)
 print('Hello again! (%s)' % threading.currentThread())


loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

觀察執(zhí)行過(guò)程:

Hello world! (<_MainThread(MainThread, started 140735195337472)>)
Hello world! (<_MainThread(MainThread, started 140735195337472)>)
(暫停約2秒)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)

由打印的當(dāng)前線程名稱可以看出,兩個(gè) coroutine 是由同一個(gè)線程并發(fā)執(zhí)行的。

如果把 asyncio.sleep() 換成真正的IO操作,則多個(gè) coroutine 就可以由一個(gè)線程并發(fā)執(zhí)行。

我們用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) # 創(chuàng)建連接
 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()
  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.sohu.com...
wget www.sina.com.cn...
wget www.163.com...
(等待一段時(shí)間)
(打印出sohu的header)
www.sohu.com header > HTTP/1.1 200 OK
www.sohu.com header > Content-Type: text/html
...
(打印出sina的header)
www.sina.com.cn header > HTTP/1.1 200 OK
www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT
...
(打印出163的header)
www.163.com header > HTTP/1.0 302 Moved Temporarily
www.163.com header > Server: Cdn Cache Server V2.0
...

可見(jiàn)3個(gè)連接由一個(gè)線程通過(guò)coroutine并發(fā)完成。

3. 小結(jié)

asyncio提供了完善的異步IO支持;

異步操作需要在coroutine中通過(guò)yield from完成;

多個(gè)coroutine可以封裝成一組Task然后并發(fā)執(zhí)行。

好了,以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論