• 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))
  • 相关阅读:
    shell备份数据库
    inux系统设置只让一个固定的ip通过ssh登录和限制连接数量
    linux服务器配置可以执行java的jar包
    sql 查询多久之前的数据
    shell将sql查询结果存放到excel中
    shell编程从初学到精通
    Redis设置键的过期时间
    Java使用redis存取集合对象
    Jpa 连接数据库自动生成实体类
    Idea 开启Run Dashboard
  • 原文地址:https://www.cnblogs.com/icemonkey/p/10474290.html
Copyright © 2020-2023  润新知