python協程

來源:互聯網
上載者:User

標籤:end   大量   .com   多線程   from   close   play   byte   get   

線程和進程的操作是由程式觸發系統介面,最後的執行者是系統,協程的操作則是人為。

協程存在的意義:對於多線程應用,cpu通過切片的方式來切換線程間的執行,線程切換時需要耗時(儲存狀態,下次繼續)。協程則只使用一個線程,在一個線程中規定某個代碼塊執行順序。

協程的使用情境:當程式中存在大量不需要cpu的操作時(IO),適用於協程。

greenlet:需要提前安裝(pip3 install greenlet,安裝完greenlet後gevent也就安裝上了)

from greenlet import greenletdef foo1():    print(‘I am foo1-gl1‘)    gl2.switch()    print(‘Who am I?‘)    gl2.switch()def foo2():    print(‘I am foo-gl2‘)    gl1.switch()    print(‘Who am I?.‘)gl1 = greenlet(foo1)gl2 = greenlet(foo2)gl1.switch()print(‘end‘)
greenlet
import gevent, timedef foo():    print(‘Running in foo‘)    gevent.sleep(0)     #通過sleep去切換到另一個任務    print(‘Explicit context switch to foo again.‘)def bar():    print(‘Explicit context switch to back to bar‘)    gevent.sleep(1)    print(‘我睡醒了‘)def func():    print(‘Explicit context switch to func.‘)    gevent.sleep(0)    print(‘I am come back‘)gevent.joinall([    gevent.spawn(foo),    gevent.spawn(bar),    gevent.spawn(func),])
gevent

 

遇到IO操作自動切換:

# monkey.patch_all()為將原來socket修改為自己的socket去發送http請求from gevent import monkey; monkey.patch_all()import gevent, requestsdef f(url):    print(‘Get: ‘,url)    resp = requests.get(url)    data = resp.text    with open(‘test‘, ‘w‘, encoding=‘utf-8‘) as f:        f.write(data)    print(‘%d bytes recceved from %s‘ % (len(data), url))gevent.joinall([    gevent.spawn(f, ‘https://www.baidu.com/‘),    gevent.spawn(f, ‘https://www.yahoo.com/‘),    gevent.spawn(f, ‘https://www.github.com/‘),])

 

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.