作業系統OS,Python - 協程(Coroutine)

來源:互聯網
上載者:User

標籤:start   def   系統   模型   star   generator   int   producer   com   

留坑例子1. 用協程實現生產者,消費者模型
  1. Python對協程的支援是通過generator實現的。
  2. 參考:49924099
  3. 參考:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432090171191d05dae6e129940518d1d6cf6eeaaa969000
"""    1. 用協程實現消費者生產者模型    2. Python對協程的支援是通過generator實現的    3. 有yield的話,就是generator"""def consumer():    r = ‘‘    while True:        # n為send過來的值        # yield類似於斷點,有兩個作用。        # 1. 產生值        # 2. 在這裡斷點,交出控制權。        n = yield r        if not n:            return        print(‘[CONSUMER] Consuming %s...‘ % n)        r = ‘200 OK‘def produce(c):     #start generator with None    c.send(None)    n = 0    while n < 5:        n = n + 1        print(‘[PRODUCER] Producing %s...‘ % n)        #啟動產生器,並附帶一個值,r接收yield產生的值        r = c.send(n)        print(‘[PRODUCER] Consumer return: %s‘ % r)    c.close()c = consumer()produce(c)

作業系統OS,Python - 協程(Coroutine)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.