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: 提供了字符集: ...
随机推荐
- Kibana6.x.x源码分析--如何自定义savedObjectType对象
上篇说到了如何使用kibana自带的savedObjectType对象,现在我们来自定义一个自己的savedObjectType. 下面的截图是我自己模仿写的保存对象,以及如何在kibana插件中注册 ...
- 通过 rundll32 创建设置注册表项权限
[Version]SIGNATURE="$Windows NT$" [DefaultInstall]AddReg=test.reg [test.reg]HKLM,"SOF ...
- [转] Kubernetes K8S 简介
[From] https://blog.csdn.net/zhangxxxww/article/details/73547251 Kubernetes(k8s)是自动化容器操作的开源平台,这些操作包括 ...
- 青蛙的约会----POJ1061
青蛙的约会 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 133905 Accepted: 29707 Descript ...
- docker run、commit报错
1.docker commit 报错 Error response from daemon: devmapper: Error mounting '/dev/mapper/docker-253:2-1 ...
- 剑指offer——面试题6:从尾到头打印链表
#include"iostream" #include"stdio.h" #include"stack" using namespace s ...
- JSON.parse(JSON.stringify()) 实现对对象的深拷贝
JSON.parse(JSON.stringify(obj))我们一般用来深拷贝,其过程说白了 就是利用JSON.stringify 将js对象序列化(JSON字符串),再使用JSON.parse来反 ...
- linux中安装软件,查看、卸载已安装软件方法
各种主流Linux发行版都采用了某种形式的包管理系统(PMS)来控制软件和库的安装. 软件包存储在服务器上,可以利用本地Linux系统上的PMS工具通过互联网访问.这些服务器称为仓库. 由于Linux ...
- JDK7之HashMap源码
并发场景下使用HashMap的问题分析:疫苗:Java HashMap的死循环 http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6423457 ...
- TCP字节流与UDP数据报(转)
关于TCP和UDP的分次发送和接收的问题,困惑了两天,看到这篇文章豁然开朗. 原文链接:http://network.51cto.com/art/201310/413326.htm “TCP是一种流模 ...