zoukankan      html  css  js  c++  java
  • 协程

    一、yield支持下的协程

     1 import time
     2 def consumer(name):    #加了yield的函数叫生成器
     3     print('...%s要吃包子...' %name)
     4     while True:
     5         new_baozi = yield
     6         print('%s is eating baozi %s' %(name,new_baozi))
     7 
     8 def producer():
     9     next(con)
    10     next(con2)
    11     print('包子制作中......')
    12     time.sleep(1)
    13     n = 0
    14     while n < 5:
    15         n += 1
    16         con.send(n)
    17         con2.send(n)
    18 
    19 
    20 if __name__ == '__main__':
    21     con = consumer('c1')       #创建生成器对象
    22     con2 = consumer('c2')
    23     p = producer()     #执行函数

    二、gevent库中greenlet支持的协程

     1 from greenlet import  greenlet
     2 
     3 def test1():
     4     print('1 2')
     5     gr2.switch()
     6     print('5 6')
     7     gr2.switch()
     8 
     9 def test2():
    10     print('3 4')
    11     gr1.switch()
    12     print('7 8')
    13 
    14 gr1 = greenlet(test1)     #创建greenlet对象
    15 gr2 = greenlet(test2)
    16 gr1.switch()     #switch开启该对象下的方法
    17 '''通过switch实现上下文的切换'''

    三、gevent库中gevent模块下的协程

     1 from gevent import monkey
     2 monkey.patch_all()   #最大程度监听I/O阻塞,节省时间
     3 import gevent
     4 def foo():
     5     print('Running in foo')
     6     gevent.sleep(1)     #模拟I/O阻塞
     7     print('Explicit context switch to foo again')
     8 
     9 def bar():
    10     print('Explicit context to bar')
    11     gevent.sleep(1)
    12     print('Implicit context switch back to bar')
    13 
    14 gevent.joinall([gevent.spawn(foo),
    15                 gevent.spawn(bar)])
    16 '''遇到I/O阻塞自动切换'''
  • 相关阅读:
    第六周例行报告
    第五周每周例行报告
    第三、四周例行报告
    PSP总结报告
    获奖感言
    20181204-1 每周例行报告
    20181127-2 每周例行报告
    软件工程原则的应用实例分析
    20181120-1 每周例行报告
    20181113-2 每周例行报告
  • 原文地址:https://www.cnblogs.com/Finance-IT-gao/p/10700406.html
Copyright © 2011-2022 走看看