python 之協程

來源:互聯網
上載者:User

標籤:共用   微線程   多個參數   線程   實現   down   無法   start   加鎖   

協程:是單線程下的並發,又稱微線程。

什麼是線程?:

協程是一種使用者態的輕量級線程,即協程是由使用者程式自己控制調度的。

協程的本質

協程的本質就是在單線程下,由使用者自己控制一個任務遇到io阻塞了就切換另外一個任務去執行,以此來提升效率

對於不涉及io的操作,單純的切換反而會降低效率

#並發執行import timedef producer():    g = consumer()    next(g)    for i in range(10000000):        g.send(i)def consumer():    while True:        res = yieldstart_time = time.time()producer()stop_time = time.time()print(stop_time-start_time)#串列import timedef producer():    res=[]    for i in range(10000000):        res.append(i)    return resdef consumer(res):    passstart_time=time.time()res=producer()consumer(res)stop_time=time.time()print(stop_time-start_time)

總結協程的優缺點:

優點

1、協程開銷小,屬於程式層級的切換,作業系統感知不到

2、單線程下可以實現並發效果, 最大限度地利用CPU

缺點

1、協程的本質是單線程下,無法利用多核優勢。

2、協程是指單線程,一旦協程出現阻塞,將會阻塞整個線程。

協程的特點:

1、必須在一個單線程裡實現並發

2、修改共用資料不加鎖

3、使用者程式自己控制儲存上下文

4、一個協程遇到io操作自動切換到其他協程。

grennlet模組

並不能監聽(不能遇到io自動切換)

from greenlet import greenletimport timedef eat(name):    print(‘%s eat 1‘ % name)    time.sleep(10)    g2.switch(‘egon‘)  # 切換    print(‘%s eat 2‘ % name)    g2.switch()def play(name):    print(‘%s play 1‘ % name)    g1.switch()    print(‘%s play 2‘ % name)g1 = greenlet(eat)g2 = greenlet(play)g1.switch(‘egon‘)
gevent模組
#用法g1=gevent.spawn(func,1,,2,3,x=4,y=5)建立一個協程對象g1,spawn括弧內第一個參數是函數名,如eat,後面可以有多個參數,可以是位置實參或關鍵字實參,都是傳給函數eat的g2=gevent.spawn(func2)g1.join() #等待g1結束g2.join() #等待g2結束#或者上述兩步合作一步:gevent.joinall([g1,g2])g1.value#拿到func1的傳回值

遇到io自動切換

import geventdef eat(name):    print(‘%s eat 1‘ %name)    gevent.sleep(2)    print(‘%s eat 2‘ %name)def play(name):    print(‘%s play 1‘ %name)    gevent.sleep(1)    print(‘%s play 2‘ %name)g1=gevent.spawn(eat,‘egon‘)g2=gevent.spawn(play,name=‘egon‘)g1.join()g2.join()#或者gevent.joinall([g1,g2])print(‘主‘)

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.