044协程

2018-06-18 02:15:29来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

内容:协程  作用:实现高并发,提高效率
##################################################################
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')
])

 



 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python全栈开发-logging模块(日记专用)

下一篇:Python 学习笔记(十四)Python类(二)