python 協程

來源:互聯網
上載者:User

標籤:import   requests   調度   odi   cer   news   from   time   encoding   

‘‘‘協成、對於非搶佔式的發送器 
1.與產生器 yleid()、儲存狀態
2.使用者態的切換、切換由使用者決定
3.協程本身是一種微線程
4.協成也是面向IO操作
5.沒有切換的消耗
6.沒有鎖的概念
‘‘‘

(1)產生器函數

def f():    print("ok")    s= yield 5    print(s)    print("ok2")    yieldgen=f()x=gen.__next__()print(x)gen.send(0)

(2)生產者消費者模型用yeild實現

import queueimport timeq=queue.Queue()def Cousumer(name):    print("準備開始吃包子>>>>>>>>")    while True:        new_baozi = yield        print("cousumer %s has eat %s baozi" %(name,new_baozi))def Producer(name):    r = con1.__next__()    r = con2.__next__()    n = 0    while 1:        time.sleep(1)        print("Producer %s  is making baozi %s and %s" %(name,n,n+1))        con1.send(n)        con2.send(n+1)        n +=2if __name__ == ‘__main__‘:   con1 =Cousumer("c1")   con2 = Cousumer("c2")   p = Producer("1號廚師")

(3)-------------greenlet 函數間的切換更加方便--------------------------

#通過 switch() 隨時切換from greenlet import greenletdef too2():    print(898)    gr1.switch()    print(34)def too1():    print(89)    gr2.switch()    print("7897978")    gr2.switch()gr1=greenlet(too1)gr2=greenlet(too2)# gr1.switch() # 動作的發起端too1()

(4)-----------------gevent介面遇到IO等待操作實現自動切換---------------------

import requests,time,geventt1=time.time()def f(url):    print("GET: %s" % url)    resp =requests.get(url)    data=resp.text    f= open("new.html","w",encoding="utf8")    f.write(data)    print("%d bytes recevied from %s" %(len(data),url))gevent.joinall([               gevent.spawn(f,"https://www.bilibili.com/video/av21663728/?p=325"),               gevent.spawn(f,"http://news.baidu.com/"),               gevent.spawn(f,"http://www.okoook.com/"),               gevent.spawn(f,"https://www.imooc.com/"),               gevent.spawn(f,"http://www.xiaohuar.com/"),               gevent.spawn(f,"http://www.xiaohuar.com/hua/"),              ])# print(time.time()-t1)#比較串列# f("https://www.bilibili.com/video/av21663728/?p=325")# f("http://news.baidu.com/")#f("http://www.okoook.com/")# f("https://www.imooc.com/")# f("http://www.xiaohuar.com/")# f("http://www.xiaohuar.com/hua/")print(time.time()-t1)

 

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.