內容:協程 作用:實現高併發,提高效率##################################################################yield支持下的協程協程是用戶輕量級線程好處:1、沒有線程切換2、無需原子操作鎖定及同步開銷3、高併發+高擴展+低成本:一個cp ...
內容:協程 作用:實現高併發,提高效率
##################################################################
yield支持下的協程
協程是用戶輕量級線程
好處:
1、沒有線程切換
2、無需原子操作鎖定及同步開銷
3、高併發+高擴展+低成本:一個cpu支持上萬的協程都沒有問題。所以很適合高併發處理
缺點:
1、無法利用多核利用——通過多進程改進
2、一個阻塞,則全部都阻塞了
def consumer(name): print('start') while True: new_baozi = yield print("[%s]is eating baozi %s" % (name,new_baozi)) def producer(): r = con.__next__() r = con2.__next__() n = 0 while n < 5: n += 1 con.send(n) con2.send(n) print("\033[32;lm[producer]\033[0m is making baozi %s" % n) if __name__ == '__main__': con = consumer('c1') con2 = consumer('c2') p = producer()
執行結果:
start
start
[c1] is eating baozi 1
[c2] is eating baozi 1
[c1] is eating baozi 2
[c2] is eating baozi 2
[c1] is eating baozi 3
[c2] is eating baozi 3
[c1] is eating baozi 4
[c2] is eating baozi 4
[c1] is eating baozi 5
[c2] is eating baozi 5
############################################################
gevent下的協程
1、安裝
搜索gevent,然後安裝
#####greenlet
from greenlet import greenlet def test1(): print(12) gr2.switch() print(34) gr2.switch() def test2(): print(56) gr1.switch() print(78) gr1 = greenlet(test1) # 建立對象 gr2 = greenlet(test2) gr1.switch() # 開始執行
執行結果:
12
56
34
78
######gevent
import gevent def foo(): print('running in foo') gevent.sleep() print('Explicit context switch to foo again') def bar(): print('Explicit context to bar') gevent.sleep() print('Implicit context switch back to bar') gevent.joinall([ gevent.spawn(foo), gevent.spawn(foo) ])
執行結果:
running in foo
Explicit context to bar
Explicit context switch to foo again
Implicit context switch back to bar
爬網站,可以明顯看出串列和併發的效果
from gevent import monkey monkey.patch_all() import gevent from urllib.request import urlopen def f(url): print('get:%s'%url) resp = urlopen(url) data = resp.read() print('%dbytesreceviedfrom%s.' % (len(data),url)) with open('xx.html','wb') as f: f.write(data) gevent.joinall([ gevent.spawn(f,'https://www.baidu.com'), #gevent.spawn(f,'192.168.10.142'), #gevent.spawn(f,'192.168.10.142:8080') ])