zoukankan      html  css  js  c++  java
  • day⑨: 协程_gevent

    Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步编程,在gevent中用到的主要模式是Greenlet, 它是以C扩展模块形式接入Python的轻量级协程。 Greenlet全部运行在主程序操作系统进程的内部,但它们被协作式地调度。


    例子: 

    gevent_同步与异步的性能区别
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    import gevent
     
    def task(pid):
        """
        Some non-deterministic task
        """
        gevent.sleep(0.5)
        print('Task %s done' % pid)
     
    def synchronous():
        for i in range(1,10):
            task(i)
     
    def asynchronous():
        threads = [gevent.spawn(task, i) for i in range(10)]
        gevent.joinall(threads)
     
    print('Synchronous:')
    synchronous()
     
    print('Asynchronous:')
    asynchronous()


    运行结果:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    D:python35python.exe D:/pycharm_project/s12/day9/协程_gevent/gevent_同步与异步的性能区别.py
    Synchronous:
    Task 1 done
    Task 2 done
    Task 3 done
    Task 4 done
    Task 5 done
    Task 6 done
    Task 7 done
    Task 8 done
    Task 9 done
    Asynchronous:
    Task 0 done
    Task 9 done
    Task 8 done
    Task 7 done
    Task 6 done
    Task 5 done
    Task 4 done
    Task 3 done
    Task 2 done
    Task 1 done






  • 相关阅读:
    2-1
    project 1
    application.properties
    springbootmybaits_day2
    springbootMybaits_day1
    linux文件夹赋予权限
    属性拼接问题
    三种数据库的配置文件db.properties
    mysql对应java中常用的字段
    Spring里面的注解
  • 原文地址:https://www.cnblogs.com/binhy0428/p/5545187.html
Copyright © 2011-2022 走看看