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()方法发送给消费者。

  • 相关阅读:
    熟练使用有棱有角的内存
    计算机进行小数运算时出错的原因
    数据是用二进制数表示的
    代码之外的功夫
    运行库实现
    系统调用与API
    运行库
    内存
    Windows下的动态链接
    Sharding-JDBC 实现垂直分库水平分表
  • 原文地址:https://www.cnblogs.com/Erick-L/p/6504942.html
Copyright © 2011-2022 走看看