Python產生器:單線程協程

來源:互聯網
上載者:User

標籤:color   並行   包子   imp   產生   pytho   print   class   end   

 1 #author F 2  3 #單線程下的並行效果 (產生器) 4 #協程 5  6 import time 7 def consumer(name): 8     print("%s 準備吃包子啦" %name) 9     while True:10         baozi = yield11         print("包子%s來啦 被%s吃啦!" %(baozi, name))12 13 c = consumer("WW")  #此時的consumer已經不是函數 他是一個產生器 此時只是初始化了一個產生器14 # c.send("[牛肉餡]")15 c.__next__()  #必須要執行一個next 語句才會走到yield處16 c.send("[豬肉餡]")  #send文法往產生器中傳參17 18 def producer(name):19     c = consumer("A")20     c2 = consumer("B")21     c.__next__()22     c2.__next__()23     print("老子開始準備做包子了!")24     for i in range(1, 11):25         time.sleep(1)26         print("做了一份包子!倆人分著吃")27         c.send(i)28         c2.send(i)29 30 producer("F")

 

Python產生器:單線程協程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.