zoukankan      html  css  js  c++  java
  • Python-协程

    协程又称微线程,在单线程里多并发

    协程修改同一份数据可以不用加锁

    协程拥有自己的寄存器上下文和栈,协程遇到IO操作就会自动切换到其它协程,协程切换时,会保留上一次调用时的状态,协程切换回来的时候,就会恢复先前保留的状态继续运行

    #-*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    from greenlet import greenlet
    
    def test1():
        print('a')
        g2.switch() #跳转到test2函数,执行print('c')
        print('b')
        g2.switch() #跳转到test2函数,到上次跳转的位置,执行print('d')
    
    def test2():
        print('c')
        g1.switch() #跳转到test1函数,到上次跳转的位置,执行print('b')
        print('d')
    if __name__ == '__main__':
        g1 = greenlet(test1)  #生成一个协程
        g2 = greenlet(test2)
        g1.switch() #启动协程
    

    运行结果

    遇到IO操作就切换,但是还是没有自动地进行io切换

    #-*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import gevent
    
    def test1():
        print('in the test1')
        gevent.sleep(2) #遇到IO操作,自动切换,切换到test3
        print('in the test1 again')
    
    def test2():
        print('in the test2')
        gevent.sleep(1) #进行IO切换,切换到test3,因为test1还在进行IO操作
        print('in the test2 again')
    
    def test3():
        print('in the test3')
        gevent.sleep(0) #0秒也会进行io切换,切换到test2
        print('in the test3 again') #执行完之后执行test1
    
    if __name__ == '__main__':
        gevent.joinall([
            gevent.spawn(test1), #生成一个协程
            gevent.spawn(test3),
            gevent.spawn(test2),
        ])
    

    运行结果

    遇到IO操作进行切换的顺序为生成协程的顺序

    运行顺序:首先执行test1函数,打印in the test1,然后遇到IO操作,切换到test3函数。在test3函数中,先打印in the test3,然后遇到IO操作,切换到test2中,打印in the test2,然后遇到test2函数中的IO操作,切换到test3函数,因为它进行IO操作为0秒,执行完test3函数后,执行test2函数,因为test1还在进行IO操作。

    整个过程只花了2秒,为最大的秒数

  • 相关阅读:
    垂死挣扎还是涅槃重生 -- Delphi XE5 公布会归来感想
    自考感悟,话谈备忘录模式
    [每日一题] OCP1z0-047 :2013-07-26 alter table set unused之后各种情况处理
    Java实现 蓝桥杯 算法提高 p1001
    Java实现 蓝桥杯 算法提高 拿糖果
    Java实现 蓝桥杯 算法提高 拿糖果
    Java实现 蓝桥杯 算法提高 求arccos值
    Java实现 蓝桥杯 算法提高 求arccos值
    Java实现 蓝桥杯 算法提高 因式分解
    Java实现 蓝桥杯 算法提高 因式分解
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8437159.html
Copyright © 2011-2022 走看看