日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
創(chuàng)新互聯(lián)Python教程:Python中的協(xié)程是什么

卓尼ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:13518219792(備注:SSL證書合作)期待與您的合作!

協(xié)程

在python GIL之下,同一時(shí)刻只能有一個(gè)線程在運(yùn)行,那么對(duì)于CPU計(jì)算密集的程序來說,線程之間的切換開銷就成了拖累,而以I/O為瓶頸的程序正是協(xié)程所擅長(zhǎng)的:

Python中的協(xié)程經(jīng)歷了很長(zhǎng)的一段發(fā)展歷程。其大概經(jīng)歷了如下三個(gè)階段:

1.最初的生成器變形yield/send;

2.引入@asyncio.coroutine和yield from;

3.在最近的Python3.5版本中引入async/await關(guān)鍵字。

(1)從yield說起

先看一段普通的計(jì)算斐波那契續(xù)列的代碼

  def fibs(n):
       res = [0] * n
       index = 0
       a = 0
       b = 1
       while index < n:
          res[index] = b
          a, b = b, a + b
          index += 1
       return res
    
    
    for fib_res in fibs(20):
       print(fib_res)

如果我們僅僅是需要拿到斐波那契序列的第n位,或者僅僅是希望依此產(chǎn)生斐波那契序列,那么上面這種傳統(tǒng)方式就會(huì)比較耗費(fèi)內(nèi)存。

這時(shí),yield就派上用場(chǎng)了。

  def fib(n):
       index = 0
       a = 0
       b = 1
       while index < n:
          yield b
          a, b = b, a + b
          index += 1
    
    for fib_res in fib(20):
       print(fib_res)

當(dāng)一個(gè)函數(shù)中包含yield語(yǔ)句時(shí),python會(huì)自動(dòng)將其識(shí)別為一個(gè)生成器。這時(shí)fib(20)并不會(huì)真正調(diào)用函數(shù)體,而是以函數(shù)體生成了一個(gè)生成器對(duì)象實(shí)例。

yield在這里可以保留fib函數(shù)的計(jì)算現(xiàn)場(chǎng),暫停fib的計(jì)算并將b返回。而將fib放入for…in循環(huán)中時(shí),每次循環(huán)都會(huì)調(diào)用next(fib(20)),喚醒生成器,執(zhí)行到下一個(gè)yield語(yǔ)句處,直到拋出StopIteration異常。此異常會(huì)被for循環(huán)捕獲,導(dǎo)致跳出循環(huán)。

(2) Send來了

從上面的程序中可以看到,目前只有數(shù)據(jù)從fib(20)中通過yield流向外面的for循環(huán);如果可以向fib(20)發(fā)送數(shù)據(jù),那不是就可以在Python中實(shí)現(xiàn)協(xié)程了嘛。

相關(guān)推薦:《Python視頻教程》

于是,Python中的生成器有了send函數(shù),yield表達(dá)式也擁有了返回值。

我們用這個(gè)特性,模擬一個(gè)慢速斐波那契數(shù)列的計(jì)算:

    import time
    import random
    
    def stupid_fib(n):
       index = 0
       a = 0
       b = 1
       while index < n:
          sleep_cnt = yield b
          print('let me think {0} secs'.format(sleep_cnt))
          time.sleep(sleep_cnt)
          a, b = b, a + b
          index += 1
    
    
    print('-' * 10 + 'test yield send' + '-' * 10)
    N = 20
    sfib = stupid_fib(N)
    fib_res = next(sfib)
    while True:
       print(fib_res)
       try:
          fib_res = sfib.send(random.uniform(0, 0.5))
       except StopIteration:
          break

python 進(jìn)行并發(fā)編程

在Python 2的時(shí)代,高性能的網(wǎng)絡(luò)編程主要是使用Twisted、Tornado和Gevent這三個(gè)庫(kù),但是它們的異步代碼相互之間既不兼容也不能移植。

asyncio是Python 3.4版本引入的標(biāo)準(zhǔn)庫(kù),直接內(nèi)置了對(duì)異步IO的支持。

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

Python的在3.4中引入了協(xié)程的概念,可是這個(gè)還是以生成器對(duì)象為基礎(chǔ)。

Python 3.5添加了async和await這兩個(gè)關(guān)鍵字,分別用來替換asyncio.coroutine和yield from。

python3.5則確定了協(xié)程的語(yǔ)法。下面將簡(jiǎn)單介紹asyncio的使用。實(shí)現(xiàn)協(xié)程的不僅僅是asyncio,tornado和gevent都實(shí)現(xiàn)了類似的功能。

(1)協(xié)程定義

用asyncio實(shí)現(xiàn)Hello world代碼如下:

    import asyncio
    
    @asyncio.coroutine
    def hello():
        print("Hello world!")
        # 異步調(diào)用asyncio.sleep(1):
        r = yield from asyncio.sleep(1)
        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(1)看成是一個(gè)耗時(shí)1秒的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(1)
        print('Hello again! (%s)' % threading.currentThread())
    
    loop = asyncio.get_event_loop()
    tasks = [hello(), hello()]
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

觀察執(zhí)行過程:

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

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

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

asyncio案例實(shí)戰(zhàn)

我們用asyncio的異步網(wǎng)絡(luò)連接來獲取sina、sohu和163的網(wǎng)站首頁(yè):

async_wget.py

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

結(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
    ...

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

小結(jié)

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

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

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


網(wǎng)頁(yè)標(biāo)題:創(chuàng)新互聯(lián)Python教程:Python中的協(xié)程是什么
文章URL:http://www.5511xx.com/article/ccchegs.html