python中利用队列asyncio.Queue进行通讯详解

本文主要给大家介绍了关于python用队列asyncio.Queue通讯的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。




asyncio.Queue与其它队列是一样的,都是先进先出,它是为协程定义的

例子如下:    

import asyncio 

  

  

async def consumer(n, q): 

 print('consumer {}:
starting'.format(n)) 

 while True: 

  print('consumer {}: waiting for
item'.format(n)) 

  item = await q.get() 

  print('consumer {}: has item {}'.format(n,
item)) 

  if item is None: 

   # None is the signal to
stop. 

  
q.task_done() 

   break

  else: 

   await asyncio.sleep(0.01 *
item) 

  
q.task_done() 

 print('consumer {}:
ending'.format(n)) 

  

  

async def producer(q, num_workers): 

 print('producer:
starting') 

 # Add some numbers to the queue to simulate
jobs 

 for i in range(num_workers *
3): 

  await q.put(i) 

  print('producer: added task {} to the
queue'.format(i)) 

 # Add None entries in the
queue 

 # to signal the consumers to
exit 

 print('producer: adding stop signals to the
queue') 

 for i in
range(num_workers): 

  await q.put(None) 

 print('producer: waiting for queue to
empty') 

 await q.join() 

 print('producer: ending') 

  

  

async def main(loop, num_consumers): 

 # Create the queue with a fixed size so the
producer 

 # will block until the consumers pull some items
out. 

 q =
asyncio.Queue(maxsize=num_consumers) 

  

 # Scheduled the consumer
tasks. 

 consumers = [ 

  loop.create_task(consumer(i,
q)) 

  for i in
range(num_consumers) 

 ] 

  

 # Schedule the producer
task. 

 prod = loop.create_task(producer(q,
num_consumers)) 

  

 # Wait for all of the coroutines to
finish. 

 await asyncio.wait(consumers
[prod]) 

  

  

event_loop = asyncio.get_event_loop() 

try: 

 event_loop.run_until_complete(main(event_loop,
2)) 

finally: 

 event_loop.close()

输出如下:    

consumer 0: starting

consumer 0: waiting for item

consumer 1: starting

consumer 1: waiting for item

producer: starting

producer: added task 0 to the queue

producer: added task 1 to the queue

consumer 0: has item 0

consumer 1: has item 1

producer: added task 2 to the queue

producer: added task 3 to the queue

consumer 0: waiting for item

consumer 0: has item 2

producer: added task 4 to the queue

consumer 1: waiting for item

consumer 1: has item 3

producer: added task 5 to the queue

producer: adding stop signals to the queue

consumer 0: waiting for item

consumer 0: has item 4

consumer 1: waiting for item

consumer 1: has item 5

producer: waiting for queue to empty

consumer 0: waiting for item

consumer 0: has item None

consumer 0: ending

consumer 1: waiting for item

consumer 1: has item None

consumer 1: ending

producer: ending

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值.

python中利用队列asyncio.Queue进行通讯详解的更多相关文章

  1. Python中生成器和yield语句的用法详解

    Python中生成器和yield语句的用法详解 在开始课程之前,我要求学生们填写一份调查表,这个调查表反映了它们对Python中一些概念的理解情况.一些话题("if/else控制流" ...

  2. python接口自动化(九)--python中字典和json的区别(详解)

    简介 这篇文章的由来是由于上一篇发送post请求的接口时候,参数传字典(dict)和json的缘故,因为python中,json和dict非常类似,都是key-value的形式,为啥还要这么传参,在群 ...

  3. python模块 re模块与python中运用正则表达式的特点 模块知识详解

    1.re模块和基础方法 2.在python中使用正则表达式的特点和问题 3.使用正则表达式的技巧 4.简单爬虫例子 一.re模块 模块引入; import re 相关知识: 1.查找: (1)find ...

  4. python中的列表(list) 切片详解

    1.切片: 通过指定下标的方式来获得某一个数据元素,或者通过指定下标范围来获得一组序列的元素,这种访问序列的方式叫做切片.    访问某一个数据元素的的语法如下:    sequence[index] ...

  5. Python中操作HTTP请求的urllib模块详解

    urllib 是 Python 标准库中用于网络请求的库.该库有四个模块,分别是urllib.request,urllib.error,urllib.parse,urllib.robotparser. ...

  6. Python中strip()、lstrip()、rstrip()用法详解

    Python中有三个去除头尾字符.空白符的函数,它们依次为: strip: 用来去除头尾字符.空白符(包括\n.\r.\t.' ',即:换行.回车.制表符.空格)lstrip:用来去除开头字符.空白符 ...

  7. Python中str.format()字典及list传入详解

  8. python中利用redis构建任务队列(queue)

    Python中的使用标准queue模块就可以建立多进程使用的队列,但是使用redis和redis-queue(rq)模块使这一操作更加简单. Part 1. 比如首先我们使用队列来简单的储存数据:我们 ...

  9. Python中利用函数装饰器实现备忘功能

    Python中利用函数装饰器实现备忘功能 这篇文章主要介绍了Python中利用函数装饰器实现备忘功能,同时还降到了利用装饰器来检查函数的递归.确保参数传递的正确,需要的朋友可以参考下   " ...

随机推荐

  1. Vue基础组件

    本文章仅用作于个人学习笔记(蓝后我就可以乱写啦)复制代码 一.组件化的优点当TodoList的todo item越来越多的时候,我们应该把它拆分成一个组件进行开发,维护.组件的出现,就是为了拆分Vue ...

  2. poj3522 苗条树(极差最小生成树)

    给你N个点和M条边 要求你求出一个生成树使得这个生成树里边权极差最小 做法① n*m做法 当最小的边已知的时候这个生成树就确定 所以最大的边也确定了 于是我们每次枚举最小的边 然后用kruskal做一 ...

  3. 安装驱动模块ko

    1. make install 2. 3.手动加载驱动程序 [root@localhost template]# modprobe usbnet [root@localhost template]# ...

  4. [uboot] (第三章)uboot流程——uboot-spl代码流程 后续2018版本分析

    board_init_f在/u-boot-2018.07-fmxx/arch/arm/mach-fmxx/spl.c中定义 board_init_f之后,和转载的部分有出入: u-boot-2018. ...

  5. @EqualsAndHashCode

    1.@Data注解包含了这些注解 * @see Getter * @see Setter * @see RequiredArgsConstructor * @see ToString * @see E ...

  6. nginx反向代理原理及配置详解

    nginx概述nginx是一款自由的.开源的.高性能的HTTP服务器和反向代理服务器:同时也是一个IMAP.POP3.SMTP代理服务器:nginx可以作为一个HTTP服务器进行网站的发布处理,另外n ...

  7. CH5105 Cookies[线性DP]

    http://contest-hunter.org:83/contest/0x50%E3%80%8C%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E3%80%8D%E4%B ...

  8. ubuntu桌面最大化

    三行命令搞定Ubuntu 16.04下安装VMware Tools!!!!!!!!! 由于下载的是ubuntu-16.04.3-desktop-amd64,需要安装vmware tools,以往提取的 ...

  9. 【JZOJ5430】【NOIP2017提高A组集训10.27】图

    题目 有一个n个点的无向图,给出m条边,每条边的信息形如\(<x,y,c,r>\) 给出q组询问形如\(<u,v,l,r>\) 接下来解释询问以及边的意义 询问表示,一开始你在 ...

  10. Spark入Hbase的四种方式效率对比

    一.方式介绍 本次测试一种采用了四种方式进行了对比,分别是:1.在RDD内部调用java API.2.调用saveAsNewAPIHadoopDataset()接口.3.saveAsHadoopDat ...