• python -- 协程


    协程

      由于python中的多线程比较特殊,所以协程的概念就变得尤为珍贵了,对于cpu密集型的操作,使用协程的效率无疑要好过多线程很多。因为协程的创建及其间切换的时间成本要低于线程很多。也因为这一点,很多人说,协程才是python的未来,重要不重要!!!

      python中提供协程的模块有两个,greenlet和gevent。greenlet和gevent最大的区别在于greenlet需要你自己来处理线程切换, 就是说,你需要自己指定现在执行哪个greenlet再执行哪个greenlet。ps:这两个包都不是python自带的,所以需要手动安装一下,pip就可以轻松搞定!

    from greenlet import greenlet
    
    def test1():
        print(12)
        gr2.switch()
        print(34)
        gr2.switch()
    
    
    def test2():
        print(56)
        gr1.switch()
        print(78)
    
    gr1 = greenlet(test1)
    gr2 = greenlet(test2)
    gr1.switch()
    
    # 最后输出结果12  56  34  78
    import gevent
    
    def func1():
        print(123)
        gevent.sleep(1)
        print(456)
    
    def func2():
        print('hahaha')
        gevent.sleep(1)
        print('10jq')
    
    g1 = gevent.spawn(func1)  # 遇见认识的io会自动切换的模块
    g2 = gevent.spawn(func2)
    g1.join()
    g2.join()
    from gevent import monkey;monkey.patch_all()
    import gevent
    import time
    import requests
    
    
    def get_url(url):
        res = requests.get(url)
        print(url,res.status_code,len(res.text))
    
    
    url_lst = [
        'http://www.sohu.com',
        'http://www.baidu.com',
        'http://www.qq.com',
        'http://www.python.org',
        'http://www.cnblogs.com',
        'http://www.mi.com',
        'http://www.apache.org'
    ]
    
    g_lst = []
    start = time.time()
    for url in url_lst:
        g = gevent.spawn(get_url, url)
        g_lst.append(g)
    gevent.joinall(g_lst)
    print(time.time() - start)
    
    start = time.time()
    for url in url_lst:
        get_url(url)
    print(time.time()-start)
  • 相关阅读:
    docker是PaaS,与openstack是IaaS的关系
    nuget安装.net standard
    GitHub sync the original repository by pull request
    Is there a way to include commas in CSV columns without breaking the formatting?
    How to determine why visual studio might be skipping projects when building a solution
    IHttpHandler vs IHttpModule
    .NET 3.0 SDK Projects not Loading
    Microsoft Edge version
    Microsoft Edge High CPU and Memory
    Google Analytics
  • 原文地址:https://www.cnblogs.com/soleZ/p/8470561.html
Copyright © 2020-2023  润新知