zoukankan      html  css  js  c++  java
  • python:协程

    1,如何实现在两个函数之间的切换?

    def func1():
        print(l)
        yield
        print(3)
        yield
    def func2():
        g =func1()
        next(g)
        print(2)
        next(g)
        print(4)
    func2()

    2,协程

    import time
    from greenlet import greenlet   # 在单线程中切换状态的模块
    def eat1():
        print('吃鸡腿1')
        g2.switch()
        time.sleep(5)
        print('吃鸡翅2')
        g2.switch()
    
    def eat2():
        print('吃饺子1')
        g1.switch()
        time.sleep(3)
        print('白切鸡')
    
    g1 = greenlet(eat1)
    g2 = greenlet(eat2)
    g1.switch()

    3,gevent

    from gevent import monkey;monkey.patch_all()
    import time     # time socket urllib requests
    import gevent   # greenlet gevent在切换程序的基础上又实现了规避IO
    from threading import current_thread
    def func1():
        print(current_thread().name)
        print(123)
        time.sleep(1)
        print(456)
    
    def func2():
        print(current_thread().name)   # dummythread
        print('hahaha')
        time.sleep(1)
        print('10jq')
    
    g1 = gevent.spawn(func1)  # 遇见他认识的io会自动切换的模块
    g2 = gevent.spawn(func2)
    gevent.joinall([g1,g2])

    4,效率对比

    from gevent import monkey;monkey.patch_all()
    import time     # time socket urllib requests
    import gevent   # greenlet gevent在切换程序的基础上又实现了规避IO
    
    def task(args):
        time.sleep(1)
        print(args)
    
    def sync_func():   # 同步
        for i in range(10):
            task(i)
    
    def async_func(): # 异步
        g_l = []
        for i in range(10):
            g_l.append(gevent.spawn(task,i))   # 给写成任务传参数
        gevent.joinall(g_l)
    
    start = time.time()
    sync_func()
    print(time.time() - start)
    
    start = time.time()
    async_func()
    print(time.time() - start)
  • 相关阅读:
    Java复制数组
    关于js正则表达式的理解
    js声明const, var, let的区别
    原生js删除多个相同类名的子元素
    python -反射hasattr、setattr、delattr
    Python-反射getattr的应用
    Python-库安装
    python -函数
    Appium -作业5(2)
    Appium appium1.6.5 使用 set_value () 输入中文,真机上无显示
  • 原文地址:https://www.cnblogs.com/kakawith/p/8431948.html
Copyright © 2011-2022 走看看