使用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. C++_类和动态内存分配6-复习各种技术及队列模拟

    知识点: 队列:是一种抽象的数据类型(Abstract Data Type),可以存储有序的项目序列. 新项目被添加在队尾,并可以删除队首的项目.队列有些像栈.栈是在同一端进行添加和删除.这使得栈是一 ...

  2. C++_类和动态内存分配4-有关返回对象的说明

    返回方式: 返回指向对象的引用: 指向对象的const引用: const对象:  =============================================== 返回指向const对象 ...

  3. rest-assured的默认值与Specification重用

    一.默认值 rest-assured发起请求时,默认使用的host为localhost,端口为8080,如果你想使用不同的端口,你可以这样做: given().port(80)...... 或者是简单 ...

  4. A Simple Math Problem(矩阵快速幂)----------------------蓝桥备战系列

    Lele now is thinking about a simple function f(x).  If x < 10 f(x) = x.  If x >= 10 f(x) = a0 ...

  5. openLayers地图缩放的回调

    //设置地图最小缩放级别为17级 map.events.register("zoomend", this, function (e) { //每次地图缩放时就会进入到这 if (m ...

  6. HihoCoder - 1172 SG函数应用

    原文讲解很nice,我尝试换种观点 设背面朝上为F,否则T, 那么局面FFFFFF肯定为0 局面FTFFFF可以转为上面局面0,设为1 局面FFTFFF可以转到0,1,设为2 子游戏SG(x)=x 对 ...

  7. MariaDB 密码,新用户添加

    修改root密码1.以root身份在终端登陆(必须)2.输入 mysqladmin -u root -p password ex后面的 ex 是要设置的密码3.回车后出现 Enter password ...

  8. [转] domeOS 环境搭建 自动化构建部署

    [From]http://dockone.io:82/article/4150 系统:CentOS Linux 7A机子(domeos服务器):1. gitlab安装(私有仓库):yum -y ins ...

  9. Linux-密码复杂度限制

    前言 设置一个复杂的密码,可以有效的提升系统的安全性.在Linux上有PAM(Pluggable Authentication Modules)里面有一个pam_cracklib.so来控制密码的复杂 ...

  10. oracle 基础知识(八)----Library Cache *

    一,介绍 Library cache是Shared pool的一部分,它几乎是Oracle内存结构中最复杂的一部分,主要存放shared curosr(SQL)和PLSQL对象(function,pr ...