• 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秒,为最大的秒数

  • 相关阅读:
    javascript实现根据时间段显示问候语的方法
    视觉会议收藏一
    cv的期刊和会议
    CVPR2016 Paper list
    CVPR 2017 Paper list
    关注的牛人
    cvpr2016论文
    linux命令技巧:scp多文件远程拷贝
    linux命令技巧--df -lh:查看磁盘占用情况
    spark--01编译安装spark1.3.1
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8437159.html
Copyright © 2020-2023  润新知