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

    1.协程

    协程,又称微线程,纤程。英文名Coroutine。 主要解决IO操作

    优点1: 协程极高的执行效率。因为子程序切换不是线程切换,是用户态切换,是由程序自身控制,因此,没有线程切换的开销,和多线程比,线程数量越多,协程的性能优势就越明显。

    优点2: 不需要多线程的锁机制,因为只有一个线程,也不存在同时写变量冲突,在协程中控制共享资源不加锁,只需要判断状态就好了,所以执行效率比多线程高很多。

    因为协程是一个线程执行,那怎么利用多核CPU呢?实现并发,最简单的方法是多进程+协程,既充分利用多核,又充分发挥协程的高效率,可获得极高的性能。

    关键字:yield send

    # 简单实例

    import
    time import queue def consumer(name): print("--->ready to eat baozi...") while True: new_baozi = yield print("[%s] is eating baozi %s" % (name,new_baozi)) #time.sleep(1) def producer(): r = con.__next__() r = con2.__next__() n = 0 while 1: time.sleep(1) print("33[32;1m[producer]33[0m is making baozi %s and %s" %(n,n+1) ) con.send(n) con2.send(n+1) n +=2 if __name__ == '__main__': con = consumer("c1") con2 = consumer("c2") p = producer()

    greenlet是一个用C实现的协程模块,相比与python自带的yield,它可以使你在任意函数之间随意切换,而不需把这个函数先声明为generator

    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
    '''
    gevent模块
    # 协程底层是通过yield来实现的
    # 协程本质上是一个线程 优势: 1.没有切换的消耗
    #                         2.没有锁的概念
    #                     问题:1.不能用cpu多核 ,可以采用多进程+协程 是解决并发的很好方案
    # grennlet协程模块
    # gevent
    
    import gevent
    import requests, time
    
    start_time = time.time()
    
    
    def f(url):
        resp = requests.get(url)
        data = resp.text
        print("%d bytes received from %s." % (len(data), url))
        with open("website.html","w",encoding="utf-8") as f:
            f.write(data)
    
    
    # 并发执行
    gevent.joinall([
        gevent.spawn(f, "https://www.python.org"),
        gevent.spawn(f, "https://www.yahoo.com"),
        gevent.spawn(f, "https://www.baidu.com"),
        gevent.spawn(f, "https://www.jd.com"),
        gevent.spawn(f, "http://www.xiaohuar.com/hua/"),
    
    ])
    
    # # 串行运行
    # f("https://www.python.org")
    # f("https://www.yahoo.com")
    # f("https://www.baidu.com")
    # f("https://www.jd.com")
    # f("http://www.xiaohuar.com/hua/")
    
    
    print("cost time: %d" % (time.time()-start_time))
  • 相关阅读:
    项目依赖库列表文件requirements.txt生成和使用
    pymysql执行sql语句无效问题
    Prometheus
    关于在安装wampserver出现“由于找不到msvcr110.dll”的问题的解决办法
    安装centos8和Window10出现的一些问题和解决方法
    LeetCode833题:字符串中的查找与替换
    Pycharm中github的使用(只有链接供自己学习使用)
    机器学习《西瓜书》的学习笔记——机器学习使用的领域
    机器学习中数理统计与参数估计的相关基础概念
    怎样在Anaconda中的某一个环境中安装Python的相关包(pypyodbc)
  • 原文地址:https://www.cnblogs.com/icemonkey/p/10474290.html
Copyright © 2011-2022 走看看