044協程

內容:協程  做用:實現高併發,提升效率
##################################################################
yield支持下的協程
協程是用戶輕量級線程
好處:
一、沒有線程切換
二、無需原子操做鎖定及同步開銷
三、高併發+高擴展+低成本:一個cpu支持上萬的協程都沒有問題。因此很適合高併發處理
缺點:
一、沒法利用多核利用——經過多進程改進
二、一個阻塞,則所有都阻塞了html

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下的協程
一、安裝
高併發

搜索gevent,而後安裝

網站

#####greenleturl

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
78spa


######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

code

 

爬網站,能夠明顯看出串行和併發的效果協程

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')
])
相關文章
相關標籤/搜索