標籤: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協程