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

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 import gevent
     4 from gevent import monkey;monkey.patch_all()
     5 import requests
     6 
     7 def f(url):
     8     print('GET:%s'% url)
     9     res = requests.get(url)
    10     data= res.text
    11     print(url,len(data))
    12 
    13 gevent.joinall(
    14     [gevent.spawn(f,'http://www.baidu.com'),
    15      gevent.spawn(f, 'http://www.qq.com'),
    16     gevent.spawn(f,'http://www.58.com'),
    17     gevent.spawn(f,'http://www.python.org'),
    18      ]
    19 )
    20 
    21 '''
    22 def foo():
    23     print('run foo.....')
    24     gevent.sleep(2)
    25     print('switch to foo.....')
    26 
    27 def bar():
    28     print('run bar.....')
    29     gevent.sleep(3)
    30     print('switch to bar.....')
    31 
    32 gevent.joinall([
    33     gevent.spawn(foo),
    34     gevent.spawn(bar)])
    35 '''

     生产者消费者模型

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    def consumer():
        last = ''
        while True:
            receival = yield last
            if receival is not None:
                print('Consume %s' % receival)
                last = receival
    
    
    def producer(gen, n):
        gen.__next__()
        x = 0
        while x < n:
            x += 1
            print('Produce %s' % x)
            last = gen.send(x)
    
        gen.close()
    
    gen = consumer()
    producer(gen, 5)

     消费者consumer()函数是一个生成器函数,每次执行到yield时即挂起,并返回上一次的结果给生产者。生产者producer()接收到生成器的返回,并生成一个新的值,通过send()方法发送给消费者。

  • 相关阅读:
    MySQL进阶(视图)---py全栈
    py基础__socket编程
    MIPS Instruction Set
    WD-保修验证(WCC7K4ARTDF1)
    Seagate-保修验证(za25shrx)
    excel-vlookup
    ebook https://salttiger.com/category/notification/
    远程登录DSM,显示“您没有权限使用本项服务?
    tplink-如何远程WEB管理路由器?
    synology terminal
  • 原文地址:https://www.cnblogs.com/Erick-L/p/6504942.html
Copyright © 2011-2022 走看看