使用asyncio.Queue

  1. import asyncio
  2. import random
  3. async def produce(queue, n):
  4. for x in range(1, n + 1):
  5. # produce an item
  6. print('producing {}/{}'.format(x, n))
  7. # simulate i/o operation using sleep
  8. await asyncio.sleep(random.random())
  9. item = str(x)
  10. # put the item in the queue
  11. await queue.put(item)
  12. # indicate the producer is done
  13. await queue.put(None)
  14. async def consume(queue):
  15. while True:
  16. # wait for an item from the producer
  17. item = await queue.get()
  18. if item is None:
  19. # the producer emits None to indicate that it is done
  20. break
  21. # process the item
  22. print('consuming item {}...'.format(item))
  23. # simulate i/o operation using sleep
  24. await asyncio.sleep(random.random())
  25. loop = asyncio.get_event_loop()
  26. queue = asyncio.Queue(loop=loop) # 队列初始化
  27. producer_coro = produce(queue, 10)
  28. consumer_coro = consume(queue)
  29. loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
  30. loop.close()

使用Queue.task_done 和 Queue.join:

  1. import asyncio
  2. import random
  3. async def produce(queue, n):
  4. for x in range(n):
  5. # produce an item
  6. print('producing {}/{}'.format(x, n))
  7. # simulate i/o operation using sleep
  8. await asyncio.sleep(random.random())
  9. item = str(x)
  10. # put the item in the queue
  11. await queue.put(item)
  12. async def consume(queue):
  13. while True:
  14. # wait for an item from the producer
  15. item = await queue.get()
  16. # process the item
  17. print('consuming {}...'.format(item))
  18. # simulate i/o operation using sleep
  19. await asyncio.sleep(random.random())
  20. # Notify the queue that the item has been processed
  21. queue.task_done()
  22. async def run(n):
  23. queue = asyncio.Queue()
  24. # schedule the consumer
  25. consumer = asyncio.ensure_future(consume(queue))
  26. # run the producer and wait for completion
  27. await produce(queue, n)
  28. # wait until the consumer has processed all items
  29. await queue.join()
  30. # the consumer is still awaiting for an item, cancel it
  31. consumer.cancel()
  32. loop = asyncio.get_event_loop()
  33. loop.run_until_complete(run(10))
  34. 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. python之列表,元组,字典。

    在博主学习列表,元组以及字典的时候,经常搞混这三者.因为他们都是用括号表示的.分别是[],(),{}. 列表(list): [1,'abc',1.26,[1,2,3],(1,2,3),{'age:18 ...

  2. Kibana6.x.x源码结构分析笔记

  3. 蓝桥-青蛙跳杯子(bfs)

    问题描述 X星球的流行宠物是青蛙,一般有两种颜色:白色和黑色. X星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去. 如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙 ...

  4. 解决分批次调用 jsonp 接口的 callback 会报错问题

    当我们分批次调用同一个jsonp接口时,会有一定机率同时调用,而jsonp的callback不支持同时调用, 会报错,所以当我们在分批次调用同一jsonp接口时,最好在callback后加个变量值,总 ...

  5. Oracle 常用函数大全

    Oracle 11g 常用函数(Functions)详解 目录 ABS. 3 ACOS. 3 ADD_MONTHS. 4 ASCII 4 ASCIISTR. 5 ASIN.. 5 ATAN.. 5 A ...

  6. flask之--钩子,异常,上下文,flask-script,模板,过滤器,csrf_token

    一.请求钩子 在客户端和服务器交互的过程中,有些准备工作或扫尾工作需要处理,比如: - 在请求开始时,建立数据库连接: - 在请求开始时,根据需求进行权限校验: - 在请求结束时,指定数据的交互格式: ...

  7. 剑指offer——面试题9:用两个栈实现队列

    #include "Queue.h" // ====================测试代码==================== void Test(char actual, ...

  8. oracle执行update语句卡住不动

    一.问题探究 开发的时候debug到一条update的sql语句时程序就不动了,然后我就在plsql上试了一下,发现plsql一直在显示正在执行,等了好久也不出结果.但是奇怪的是执行其他的select ...

  9. vuex中filter的使用 && 快速判断一个数是否在一个数组中

    vue中filter的使用 computed: mapState({ items: state => state.items.filter(function (value, index, arr ...

  10. 在lua中解决if else switch问题

    之前写过一个c#版本的使用字典去解决switch问题  http://www.cnblogs.com/sanyejun/p/7806210.html 现在用写lua版本的 function Main( ...