queue隊列,以及生產者消費者模型
queue
隊列!特點是有序的,跟list的區別,list調用元素,其實就是復制,還要用remove給刪掉,麻煩,queue更加方便
生成隊列的方法:
class queue.
Queue
(maxsize=0) #先入先出 #maxsize可以設定隊列大小
class queue.
LifoQueue
(maxsize=0) #last in fisrt out 後進先出,例如賣東西,大家都喜歡新鮮的
class queue.
PriorityQueue
(maxsize=0) #存儲數據時可設置優先級的隊列
#PriorityQueue VIP!! #例子 import queue q=queue.PriorityQueue() q.put((18,‘qiangql‘)) q.put((2,‘egbert‘)) q.put((39,‘boboka‘)) print(q.get( )) print(q.get( )) print(q.get( )) #運行結果 (2, ‘egbert‘) (18, ‘qiangql‘) (39, ‘boboka‘)
基本語法:
存數據
Queue.put()
取數據
Queue.get(block=True, timeout=None) #block 堵塞,默認是Ture,娶不到數據卡主,timeout等待時間,最多等多久
判斷隊列大小 #當前隊列大小
Queue.qsize()
設置隊列大小
Queue(maxsize=99)
驗證隊列是否為空,返回真,假
Queue.empty()
Queue.task_done() #還沒看一會補充
Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get()
used to fetch a task, a subsequent call to task_done()
tells the queue that the processing on the task is complete.
If a join()
is currently blocking, it will resume when all items have been processed (meaning that a task_done()
call was received for every item that had been put()
into the queue).
Raises a ValueError
if called more times than there were items placed in the queue.
生產者消費者模型
例子1:
import threading,time import queue def producer(): count=1 while True: q.put(‘骨頭%s‘%count) print(‘生產骨頭%s‘%count) count+=1 time.sleep(0.5) def consumer(name): while True: print("%s 取到%s" %(name, q.get())) time.sleep(1.5) q = queue.Queue(maxsize=10) p = threading.Thread(target=producer, ) p.start() c1 = threading.Thread(target=consumer,args=(‘qianglq‘,)) c2 = threading.Thread(target=consumer,args=(‘buring‘,)) c1.start() c2.start()
執行結果:
生產骨頭1
qianglq 取到骨頭1
生產骨頭2
buring 取到骨頭2
生產骨頭3
生產骨頭4
qianglq 取到骨頭3
buring 取到骨頭4
生產骨頭5
生產骨頭6
生產骨頭7
qianglq 取到骨頭5
生產骨頭8
buring 取到骨頭6
生產骨頭9
生產骨頭10
例子2
import threading import queue def producer(): for i in range(10): q.put("骨頭 %s" % i) print("開始等待所有的骨頭被取走...") q.join() print("所有的骨頭被取完了...") def consumer(n): while q.qsize() > 0: print("%s 取到" % n, q.get()) q.task_done() # 告知這個任務執行完了 q = queue.Queue() p = threading.Thread(target=producer, ) p.start() c1 = consumer("43輪") 執行結果: 開始等待所有的骨頭被取走... 43輪 取到 骨頭 0 43輪 取到 骨頭 1 43輪 取到 骨頭 2 43輪 取到 骨頭 3 43輪 取到 骨頭 4 43輪 取到 骨頭 5 43輪 取到 骨頭 6 43輪 取到 骨頭 7 43輪 取到 骨頭 8 43輪 取到 骨頭 9 所有的骨頭被取完了...
queue隊列,以及生產者消費者模型