使用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. checkstyle 各标签 (有几个没翻译,不懂意思)

    以下是对checkstyle 7.8.1 version各标签的翻译,有少数几个标签没翻译,不太懂官网的意思,就空了,希望游客能帮忙补充补充,另外有错的话也希望大家留言下哈,另外转载的话请标明一下 1 ...

  2. C++_类继承5-抽象基类

    abstract base class,ABC 抽象基类 有时候is-a规则并不像看上去那么简单,例如圆和椭圆的关系.圆是椭圆的特殊情况.椭圆可以派生出圆.但是椭圆的数据成员及方法对于圆来说是信息冗余 ...

  3. abp框架angular 项目docker 手动部署到Linux环境中

    1.https://aspnetboilerplate.com/Templates 2.后端项目发布,在publish中abp默认已经存在DockerFile文件 3.修改后端文件中的DockerFi ...

  4. JavaScript笔记Array.filter(Boolean)

    ECMAScirpt5 中 Array 类中的 filter 方法使用目的是移除所有的 ”false“ 类型元素  (false, null, undefined, 0, NaN or an empt ...

  5. hdu 2570 贪心

    贪心的经典题型 该死的精度问题,WA了好几次,以后能用乘的绝不用除!! #include<iostream> #include<algorithm> #include<c ...

  6. Linux mysql中文乱码问题

    1.debian系统 (1)mysql 5.5版本之前 vim /etc/mysql/my.cnf 在  [client]  下面加入 default-character-set=utf8 在  [m ...

  7. 零基础搭建 spring mvc 4 项目(本文基于 Servlet 3.0)

    作者各必备工具的版本如下: Tomcat:apache-tomcat-7.0.63 (下载链接) Java EE - Eclipse:Luna Service Release 1 v4.4.1 (下载 ...

  8. JavaEE 数据库随机值插入测试

    package com.jery.javaee.dbtest; import java.sql.Connection; import java.sql.DriverManager; import ja ...

  9. resty-limit-multiple-strategy.lua

    --[[ 执行过载限流策略 --]] -- 当执行限流时,Nginx 返回的状态码 err_code = local limit_config = { user_limit = {rate = , b ...

  10. python 管理多版本之pyenv

    一, [root@management ~]# pyenv install -listAvailable versions:  3.3.0  3.3.1  3.3.2  3.3.3  3.3.4  3 ...