[PY3]——Queue
Queue
class Queue(builtins.object)
__init__(self, maxsize=0) empty(self) full(self) get(self, block=True, timeout=None) get_nowait(self) put(self, item, block=True, timeout=None) put_nowait(self, item) join(self) task_done(self) qsize(self)
Queue
创建一个给定最大大小(maxsize)的队列对象
if maxsize<=0,队列大小为无限大
put(self, item, block=True, timeout=None)
将item放入队列中
if block=True,timeout=None:阻塞调用,无超时
if timeout=N(N为正整数):超过N时间队列无空间可put,抛出Full异常
if block=False:只要有空闲空间就将item put入队列,否则抛出Full异常
put_nowait()
相当于put(block=False)
get(self, block=True, timeout=None)
将item移出队列
要注意:get()没有item参数,Queue是一个FIFO队列,只能是先进先出。即get的顺序是由put的顺序决定了。
if block=True,timeout=None:无超时,直到有item可get
if block=True,timeout=N:超过N时间队列还是无item可get,raise Empty
if block=Flase,timeout=None:只要有item就立刻get,否则raise Empty
get_nowait()
相当于get(block=False)
empty(self)
判断队列是否为空
空则返回True、反之返回False
task_done(self)
向完成的队列发送一个信号
qsize(self)
返回队列大小
queue=Queue(maxsize=5) # 设最大长度为5 print(queue.empty())
True for i in range(1,6):
queue.put(item=i) print(queue.full())
True print(queue.qsize()) print(queue.put(item=9,timeout=3)) #超过3秒,queue已无空间可put,抛出Full异常
queue.Full ### get():删除指定长度的元素 ###
# Example-1
val=[]
for i in range(1,3): # 这个循环就决定删除的item个数,跟item的索引和值都没啥关系...
val.append(queue.get()) print(val) # get()的返回值是删除的item值
[1,2] print(queue.full())
False print(queue.qsize()) # Example-2
print(queue.qsize()) val=[]
while not queue.qsize()==2:
try:
val.append(queue.get())
except:
break
print(val)
[1, 2, 3] ### get():删除全部队列全部元素 ###
print(queue.qsize()) val=[]
while not queue.empty():
val.append(queue.get()) print(val)
[1, 2, 3, 4, 5]
Queue+Threading
import random,time
import threading
import logging
from queue import Queue logging.basicConfig(level=logging.DEBUG,format='%(asctime)s [%(threadName)s] %(message)s',datefmt="%H:%M:%S") class Producer(threading.Thread): # Pro-Thread:产生长度为10的队列
def __init__(self,name,queue):
threading.Thread.__init__(self,name=name)
self.data=queue def run(self):
for i in range(5):
randomnum=random.randint(1,99)
self.data.put(randomnum)
logging.info("{} put item in Queue".format(randomnum))
logging.info("Finished put item in Queue") class Consumer_even(threading.Thread): # Even-Thread:取出队列中的偶数
def __init__(self,name,queue):
threading.Thread.__init__(self,name=name)
self.data=queue def run(self):
while 1:
try:
val_even=self.data.get(block=True,timeout=5) # 超过5sget不到item了,则执行except部分 # 可以只单单运行start Even-Thread看看,except不了的
if val_even%2==0:
logging.info("{} even is consumed".format(val_even))
time.sleep(2)
else:
self.data.put(val_even)
time.sleep(2)
except:
logging.info("even finished")
break class Consumer_odd(threading.Thread): # Odd—Thread:取出队列中的奇数
def __init__(self,name,queue):
threading.Thread.__init__(self,name=name)
self.data=queue def run(self):
while 1:
try:
val_odd=self.data.get(block=True,timeout=5)
if val_odd%2!=0:
logging.info("{} odd is consumed".format(val_odd))
time.sleep(2)
else:
self.data.put(val_odd)
time.sleep(2)
except:
logging.info("odd finished")
break def main():
queue=Queue()
producer=Producer('Pro',queue)
consumer_even=Consumer_even("Even",queue)
consumer_odd=Consumer_odd("Odd",queue) threads=[producer,consumer_even,consumer_odd] for thread in threads:
thread.start() for thread in threads:
thread.join() print(queue.empty()) if __name__ == '__main__':
main()
Reference Article
[PY3]——Queue的更多相关文章
- collections, time, queue的应用
collections (克来克深思) Counter from collections import Counter # 引入模块, 计数器 Counter(康特) s = 'sadfasdfas ...
- python---基础知识回顾(十)进程和线程(py2中自定义线程池和py3中的线程池使用)
一:自定义线程池的实现 前戏: 在进行自定义线程池前,先了解下Queue队列 队列中可以存放基础数据类型,也可以存放类,对象等特殊数据类型 from queue import Queue class ...
- py3.x和py2.x的区别
1.性能 Py3.0运行 pystone benchmark的速度比Py2.5慢30%.Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可 以取得很好的优化结果. Py3.1性能比Py2 ...
- [数据结构]——链表(list)、队列(queue)和栈(stack)
在前面几篇博文中曾经提到链表(list).队列(queue)和(stack),为了更加系统化,这里统一介绍着三种数据结构及相应实现. 1)链表 首先回想一下基本的数据类型,当需要存储多个相同类型的数据 ...
- Azure Queue Storage 基本用法 -- Azure Storage 之 Queue
Azure Storage 是微软 Azure 云提供的云端存储解决方案,当前支持的存储类型有 Blob.Queue.File 和 Table. 笔者在<Azure File Storage 基 ...
- C++ std::queue
std::queue template <class T, class Container = deque<T> > class queue; FIFO queue queue ...
- 初识Message Queue之--基础篇
之前我在项目中要用到消息队列相关的技术时,一直让Redis兼职消息队列功能,一个偶然的机会接触到了MSMQ消息队列.秉着技术还是专业的好为原则,对MSMQ进行了学习,以下是我个人的学习笔记. 一.什么 ...
- 搭建高可用的rabbitmq集群 + Mirror Queue + 使用C#驱动连接
我们知道rabbitmq是一个专业的MQ产品,而且它也是一个严格遵守AMQP协议的玩意,但是要想骚,一定需要拿出高可用的东西出来,这不本篇就跟大家说 一下cluster的概念,rabbitmq是erl ...
- PriorityQueue和Queue的一种变体的实现
队列和优先队列是我们十分熟悉的数据结构.提供了所谓的“先进先出”功能,优先队列则按照某种规则“先进先出”.但是他们都没有提供:“固定大小的队列”和“固定大小的优先队列”的功能. 比如我们要实现:记录按 ...
随机推荐
- 【转】【译】在 Windows 10 应用程序中注册任意依赖属性的改变
原文地址:http://visuallylocated.com/post/2015/04/01/Registering-to-any-DependencyProperty-changing-in-Wi ...
- Excel 帮助无法正常工作的解决方法
Excel 中出现错误:帮助无法正常工作,但您仍可以转到 Office.com,以获得最新和最好的文章.视频和培训课程. 英文消息:Help isn't working, but you can st ...
- JS——图片预览功能
<script type="text/javascript"> function DisplayImage(fileTag) { document. ...
- C#在dataGridView中遍历,寻找相同的数据并定位
1. C#在dataGridView中遍历,寻找相同的数据并定位 [c-sharp] view plain copy int row = dataGridView1.Rows.Count;// ...
- C# 实现图片压缩
代码: private static ImageCodecInfo GetImageCodecInfo(ImageFormat imageFormat) { ImageCodecInfo[] imag ...
- kernel 调试 打印IP地址
#define NIPQUAD(addr) \ ((unsigned char *)&addr)[0], \ ((unsigned char *)&addr)[1], \ ((unsi ...
- AGC032D Rotation Sort
题目传送门 Description 给定\(N\)的排列(\(N\leq5000\)),将任一区间最左侧的数插到该区间最右边的代价为\(A\),将任一区间最右侧的数插到该区间最左边的代价为\(B\), ...
- hdoj1435 Stable Match(稳定婚姻问题)
简单稳定婚姻问题. 题目描述不够全面,当距离相同时容量大的优先选择. 稳定婚姻问题不存在无解情况. #include<iostream> #include<cstring> # ...
- 程序猿的日常——Java基础之clone、序列化、字符串、数组
其实Java还有很多其他的基础知识,在日常工作技术撕逼中也是经常被讨论的问题. 深克隆与浅克隆 在Java中创建对象有两种方式: 一种是new操作符,它创建了一个新的对象,并把对应的各个字段初始化成默 ...
- 详述MySQL服务在渗透测试中的利用
本文作者:i春秋签约作家——Binghe 致力于书写ichunqiu社区历史上最长篇最细致最真实的技术复现文章. 文章目录: MySQL之UDF提权 MySQL之MOF提权 MySQL之常规写启动项提 ...