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)
  • 相关阅读:
    恼人的CON(转)
    CINRAD/SB 多普勒天气雷达
    如何将两个栅格数据图层求和并求并集
    javascript设置asp.net程序开始运行时ie最大化显示
    ArcGIS Engine中数据的加载(转载)
    发现了一个arcgis engine的一个bug
    带余除法
    第二数学归纳法
    concat和concat_ws()区别及MySQL的几个实用字符串函数
    oracle查询语句大全
  • 原文地址:https://www.cnblogs.com/kakawith/p/8431948.html
Copyright © 2011-2022 走看看