[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())
5

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())
3

# Example-2
print(queue.qsize())
5
val=[]
while not queue.qsize()==2:
    try:
        val.append(queue.get())
    except:
        break
print(val)
[1, 2, 3]


### get():删除全部队列全部元素 ###
print(queue.qsize())
5

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

《Python Queue模块处理》

《Python队列Queue》

《Python异常处理》

posted @ 2017-09-21 12:02  Jelly_lyj  阅读(105)  评论(0编辑  收藏  举报