- queue is especially useful in threaded programming when information must be exchanged safely between multiple threads
- queue在使用多進程之間交換安全信息的時候特別有用
-
class
queue.Queue(maxsize=0) #先入先出
-
class
queue.LifoQueue(maxsize=0) #last in fisrt out -
class
queue.PriorityQueue(maxsize=0) #存儲數據時可設置優先級的隊列 優先級最小最先取出 -
exception
queue.Empty 正常情況下當隊列為空則阻塞,如果設置了get_nowaait則會報該異常 -
Exception raised when non-blocking
get()(orget_nowait()) is called on aQueueobject which is empty. -
exception
queue.Full 當設置了put_nowait,隊列滿時報異常
Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full.
-
Queue.qsize() 查看隊列大小
-
Queue.empty() #return True if empty 隊列為空返回True
-
Queue.full() # return True if full
-
Queue.put(item, block=True, timeout=None) 上傳到隊列 正常當Q滿了 在put就阻塞 如果timeout為True 則等待多少秒后直接拋異常
-
Queue.put_nowait(item)# 隊列滿直接拋異常 -
Queue.get(block=True, timeout=None) #上傳到隊列,隊列空了阻塞 -
Queue.get_nowait() 隊列沒數據直接拋異常 -
Queue.task_done() # q.task_done() 在完成一項工作之后,q.task_done() 函數向任務已經完成的隊列發送一個信號.
-
Queue.join() 實際上意味着等到隊列為空,再執行別的操作
#!/usr/bin/env python # -*- coding:utf-8 -*- import queue class Foo(object): def __init__(self,n): self.n = n #q = queue.Queue(maxsize=30) #q = queue.LifoQueue(maxsize=30) q = queue.PriorityQueue(maxsize=30) q.put((2,[1,2,3])) #q.put(Foo(1)) q.put((10,1)) q.put((3,1)) q.put((5,30)) q.task_done() q.join() print(q.get()) print(q.get()) print(q.get()) print(q.get())
生產者消費者模型
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading,queue import time def consumer(n): while True: print("\033[32;1mconsumer [%s]\033[0m get task: %s" % (n,q.get())) time.sleep(1) q.task_done()#每get一次包子,像其他進程告知隊列信息 def producer(n): count = 1 while True: #time.sleep(1) #if q.qsize() <3: print("prodcer [%s] produced a new task : %s" %(n,count)) q.put(count) count +=1 q.join() #queue is emtpy # 等到隊列為空在繼續往下執行 print("all taks has been cosumed by consumers...") q = queue.Queue() c1 = threading.Thread(target=consumer,args=[1,]) c2 = threading.Thread(target=consumer,args=[2,]) c3 = threading.Thread(target=consumer,args=[3,]) p = threading.Thread(target=producer,args=["XiaoYu",]) p2 = threading.Thread(target=producer,args=["LiuYao",]) c1.start() c2.start() c3.start() p.start() p2.start()
