zoukankan      html  css  js  c++  java
  • 协程

    一.协程

      协程就是在线程中开线程,由用户自己控制,也叫微线程,必须在单线程中实现并发

    二.生成器版协程

      使用yield保持状态,使用next()切换任务,并不能合理利用I/O阻塞并发,提升效率.

    import time
    # 没有节省时间
    def f1():
        for i in range(10):
            time.sleep(0.2)
            print(i)
            yield           # 生成器可以帮忙记录状态
    
    def f2():
        g = f1()
        for i in range(10):
            next(g)             # 你一下,我一下    类似于切换任务
            print(i)
    
    f1()
    f2()
    生成器版协程

    三.greenlet模块版协程

      greenlet模块帮助我们保持状态+任务切换

    import time
    from greenlet import greenlet  # 了解
    
    def f1():
        print("f1")
        g2.switch()         # 保持状态,然后切换
        time.sleep(1)
        print("f1")
        g2.switch()
    
    def f2():
        print("f2")
        g1.switch()
        time.sleep(2)
        print("f2")
    
    g1 = greenlet(f1)
    g2 = greenlet(f2)
    g2.switch()         # switch() 也可以传参,在第一次的时候传参就行 保持状态 + 切换任务
    greenlet模块协程

    1.greenlet模块中的方法

      g = greenlet(function)  创建一个对象

      g.switch(参数)  用于保持状态和切换任务

    四.gevent模块版协程

      gevent模块帮助我们模拟操作体统来切换任务,

    from gevent import monkey;monkey.patch_all
    import gevent
    
    def f1():
        print(1)
        # print(threading.current_thread().getName())
        time.sleep(1)
        print("f1")
    
    def f2():
        print(2)
        # print(threading.current_thread().getName())
        gevent.sleep(2)
        print("f2")
    
    g1 = gevent.spawn(f1)
    g2 = gevent.spawn(f2)
    
    gevent.joinall([g1,g2])  # g1.join()  g2.join() 等效
    gevent模块版协程

    1.gevent模块中的方法

      g = gevent.spawn(function)  创建一个greenlet对象

      gevent.joinall([g])  和g.join() 一样,方便一次使用多个join()

  • 相关阅读:
    算法时间复杂度、空间复杂度(大O表示法)
    六、Java“毒丸”使用示例,实现取消任务
    四、获取IP地址工具包
    SEDA架构程序实现
    二十一、curator recipes之TreeCache
    二十、curator recipes之NodeCache
    十九、curator recipes之PathChildrenCache
    十八、curator recipes之DistributedDelayQueue
    Mysql学习笔记【一、环境安装&配置】
    Go学习笔记【一、概述】
  • 原文地址:https://www.cnblogs.com/q767498226/p/10268988.html
Copyright © 2011-2022 走看看