zoukankan      html  css  js  c++  java
  • 协程

    # 协程 协作 非抢占式 编程者自己调度
    # 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)
  • 相关阅读:
    PHP -----上传文件
    PHP----预定义数组
    PHP-------- 会话控制
    PHP------XML
    PHP----练习-----三级联动
    PHP-------ajax返回值 返回JSON 数据
    PHP----练习----光标离开文本框时变色
    使用ansible安装配置zabbix客户端
    svn+apache安装配置
    rsync+lsyncd实现实时同步
  • 原文地址:https://www.cnblogs.com/dangrui0725/p/9499509.html
Copyright © 2011-2022 走看看