使用asyncio.Queue

import asyncio
import random async def produce(queue, n):
for x in range(1, n + 1):
# produce an item
print('producing {}/{}'.format(x, n))
# simulate i/o operation using sleep
await asyncio.sleep(random.random())
item = str(x)
# put the item in the queue
await queue.put(item) # indicate the producer is done
await queue.put(None) async def consume(queue):
while True:
# wait for an item from the producer
item = await queue.get()
if item is None:
# the producer emits None to indicate that it is done
break # process the item
print('consuming item {}...'.format(item))
# simulate i/o operation using sleep
await asyncio.sleep(random.random()) loop = asyncio.get_event_loop()
queue = asyncio.Queue(loop=loop) # 队列初始化
producer_coro = produce(queue, 10)
consumer_coro = consume(queue)
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
loop.close()

使用Queue.task_done 和 Queue.join:

import asyncio
import random async def produce(queue, n):
for x in range(n):
# produce an item
print('producing {}/{}'.format(x, n)) # simulate i/o operation using sleep
await asyncio.sleep(random.random())
item = str(x) # put the item in the queue
await queue.put(item) async def consume(queue):
while True:
# wait for an item from the producer
item = await queue.get() # process the item
print('consuming {}...'.format(item)) # simulate i/o operation using sleep
await asyncio.sleep(random.random()) # Notify the queue that the item has been processed
queue.task_done() async def run(n):
queue = asyncio.Queue() # schedule the consumer
consumer = asyncio.ensure_future(consume(queue)) # run the producer and wait for completion
await produce(queue, n) # wait until the consumer has processed all items
await queue.join() # the consumer is still awaiting for an item, cancel it
consumer.cancel() loop = asyncio.get_event_loop()
loop.run_until_complete(run(10))
loop.close()

asyncio标准库7 Producer/consumer的更多相关文章

  1. python协程(yield、asyncio标准库、gevent第三方)、异步的实现

    引言 同步:不同程序单元为了完成某个任务,在执行过程中需靠某种通信方式以协调一致,称这些程序单元是同步执行的. 例如购物系统中更新商品库存,需要用"行锁"作为通信信号,让不同的更新 ...

  2. asyncio标准库6 Threads & Subprocess

    Threads import asyncio def compute_pi(digits): # implementation return 3.14 async def main(loop): di ...

  3. asyncio标准库5 TCP echo client and server

    server import asyncio async def handle_echo(reader, writer): data = await reader.read(100) message = ...

  4. asyncio标准库4 asyncio performance

    性能包括2部分 每秒并发请求数(Number of concurrent requests per second) 每秒请求负载(Request latency in seconds: min/ave ...

  5. asyncio标准库3 HTTP client example

    import aiohttp import asyncio import async_timeout async def fetch(session, url): async with async_t ...

  6. asyncio标准库2 Hello Clock

    如何调度协程,并发运行 asyncio.gather方法可以聚合协程or future def gather(*coros_or_futures, loop=None, return_exceptio ...

  7. asyncio标准库1 Hello World

    利用asyncio的event loop,编写和调度协程 coroutine [,kəuru:'ti:n] n. 协程 Simple coroutine(调用1个协程) import asyncio ...

  8. python第六天 函数 python标准库实例大全

    今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...

  9. 转--Python标准库之一句话概括

    作者原文链接 想掌握Python标准库,读它的官方文档很重要.本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了. 文本处理 string: 提供了字符集: ...

随机推荐

  1. DropDownList绑定及修改

    DropDownList绑定及修改 http://www.cnblogs.com/hulang/archive/2010/12/29/1920662.html   ? 1 2 3 4 5 6 7 8 ...

  2. HDU6464 (权值线段树)-(查找区间第k1小于第k2小之间的和)

    http://acm.hdu.edu.cn/showproblem.php?pid=6464 不理解先看博客:https://blog.csdn.net/g21glf/article/details/ ...

  3. C# 字符串操作,可空类型,文档注释,嵌套类型

    字符串 字符串是Unicode字符串数组,且是不可变的 这种操作不会影响到原来的字符串,它会新添加一个副本. 有关Split的操作 using System; using System.Collect ...

  4. js关于原型,原型链的面试题

    之前面试的时候遇到过原型和原型链方面的题目,具体的已经忘了,只记得当时回答的稀里糊涂,今天查了一些资料,把自己所理解的写出来,加深记忆. 1,前提 在js中,对象都有__proto__属性,一般这个是 ...

  5. pycharm 安装tushare

    1.教程非常简单,但是我确研究了整整一个晚上,分享下经历 2.安装tushare包的时候,先要安装5个依赖包 lxml,beautifulsoup4,pandas,requests,simplejso ...

  6. vue dev 环境下的跨域访问

    概述:被dev环境下的跨域弄晕了好几天,build环境还在研究中 1.config--->index.js---->module.exports---->dev 2.在main.js ...

  7. PIE SDK影像格式转换

      1.算法功能简介 影像格式转换可以实现通用栅格数据格式之间的自由转换.可自由转换的格式包括: GeoTIFF. ERDAS img. ENVI img. PIE支持算法功能的执行,下面对影像格式转 ...

  8. Linux批量杀掉挂掉的进程

    $ `ps aux | grep test | grep -v grep | awk '{print $2}'` 杀掉含有test且不含有grep的进程,后面的 awk '{print $2}' 是进 ...

  9. GreenPlum 大数据平台--介绍

    一,GreenPlum 01,介绍: Greenplum是一种基于PostgreSQL的分布式数据库,其采用shared-nothing架构,主机.操作系统.内存.存储都是自我控制的,不存在共享. 官 ...

  10. shell 进阶之匹配字符串

      一,操作字符串 1,字符串长度 expr 命令取字符串函数 自带shell函数读取 2,匹配字符串开头字串的长度   !!!!!!!!!!!!$substring是正则表达式.!!!!!!!!! ...