• 协程


    # 协程 协作 非抢占式 编程者自己调度
    # 1、通过生成器
    import time
    
    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()
    
    # 2、通过greenlet协程模块
    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()
    
    # 3、Gevent
    import gevent
    
    import requests, time
    
    start = time.time()
    
    
    def f(url):
        print('GET: %s' % url)
        resp = requests.get(url)
        data = resp.text
        print('%d bytes received from %s.' % (len(data), url))
    
    
    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.sina.com.cn/'),
    
    ])
    
    # 串行去爬网页
    # f('https://www.python.org/')
    #
    # f('https://www.yahoo.com/')
    #
    # f('https://baidu.com/')
    #
    # f('https://www.sina.com.cn/')
    
    print("cost time:", time.time() - start)
  • 相关阅读:
    LeetCode-6 ZigZag Conversion
    求两个字符串的最长公共子串
    Eclipse 添加 javap
    时间复杂度
    leetcode oj-3
    Android Rom分区 与 SD卡读写
    论文首次处理流程及代码
    论文片段
    项目整体流程
    春晚项目中的相关脚本
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9499509.html
Copyright © 2020-2023  润新知