asyncio标准库7 Producer/consumer
使用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的更多相关文章
- python协程(yield、asyncio标准库、gevent第三方)、异步的实现
引言 同步:不同程序单元为了完成某个任务,在执行过程中需靠某种通信方式以协调一致,称这些程序单元是同步执行的. 例如购物系统中更新商品库存,需要用"行锁"作为通信信号,让不同的更新 ...
- asyncio标准库6 Threads & Subprocess
Threads import asyncio def compute_pi(digits): # implementation return 3.14 async def main(loop): di ...
- asyncio标准库5 TCP echo client and server
server import asyncio async def handle_echo(reader, writer): data = await reader.read(100) message = ...
- asyncio标准库4 asyncio performance
性能包括2部分 每秒并发请求数(Number of concurrent requests per second) 每秒请求负载(Request latency in seconds: min/ave ...
- asyncio标准库3 HTTP client example
import aiohttp import asyncio import async_timeout async def fetch(session, url): async with async_t ...
- asyncio标准库2 Hello Clock
如何调度协程,并发运行 asyncio.gather方法可以聚合协程or future def gather(*coros_or_futures, loop=None, return_exceptio ...
- asyncio标准库1 Hello World
利用asyncio的event loop,编写和调度协程 coroutine [,kəuru:'ti:n] n. 协程 Simple coroutine(调用1个协程) import asyncio ...
- python第六天 函数 python标准库实例大全
今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...
- 转--Python标准库之一句话概括
作者原文链接 想掌握Python标准库,读它的官方文档很重要.本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了. 文本处理 string: 提供了字符集: ...
随机推荐
- python之列表,元组,字典。
在博主学习列表,元组以及字典的时候,经常搞混这三者.因为他们都是用括号表示的.分别是[],(),{}. 列表(list): [1,'abc',1.26,[1,2,3],(1,2,3),{'age:18 ...
- Kibana6.x.x源码结构分析笔记
- 蓝桥-青蛙跳杯子(bfs)
问题描述 X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色. X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去. 如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙 ...
- 解决分批次调用 jsonp 接口的 callback 会报错问题
当我们分批次调用同一个jsonp接口时,会有一定机率同时调用,而jsonp的callback不支持同时调用, 会报错,所以当我们在分批次调用同一jsonp接口时,最好在callback后加个变量值,总 ...
- Oracle 常用函数大全
Oracle 11g 常用函数(Functions)详解 目录 ABS. 3 ACOS. 3 ADD_MONTHS. 4 ASCII 4 ASCIISTR. 5 ASIN.. 5 ATAN.. 5 A ...
- flask之--钩子,异常,上下文,flask-script,模板,过滤器,csrf_token
一.请求钩子 在客户端和服务器交互的过程中,有些准备工作或扫尾工作需要处理,比如: - 在请求开始时,建立数据库连接: - 在请求开始时,根据需求进行权限校验: - 在请求结束时,指定数据的交互格式: ...
- 剑指offer——面试题9:用两个栈实现队列
#include "Queue.h" // ====================测试代码==================== void Test(char actual, ...
- oracle执行update语句卡住不动
一.问题探究 开发的时候debug到一条update的sql语句时程序就不动了,然后我就在plsql上试了一下,发现plsql一直在显示正在执行,等了好久也不出结果.但是奇怪的是执行其他的select ...
- vuex中filter的使用 && 快速判断一个数是否在一个数组中
vue中filter的使用 computed: mapState({ items: state => state.items.filter(function (value, index, arr ...
- 在lua中解决if else switch问题
之前写过一个c#版本的使用字典去解决switch问题 http://www.cnblogs.com/sanyejun/p/7806210.html 现在用写lua版本的 function Main( ...