queue訊息佇列
-
class
queue.
Queue
(maxsize=0 ) #先入先出
-
class
queue.
LifoQueue
(maxsize=0 ) #last in fisrt out -
class
queue.
PriorityQueue
(maxsize=0 ) #儲存資料時可設定優先順序的佇列
生產者消費者模型
在併發程式設計中使用生產者和消費者模式能夠解決絕大多數併發問題。該模式通過平衡生產執行緒和消費執行緒的工作能力來提高程式的整體處理資料的速度。
為什麼要使用生產者和消費者模式
線上程世界裡,生產者就是生產資料的執行緒,消費者就是消費資料的執行緒。在多執行緒開發當中,如果生產者處理速度很快,而消費者處理速度很慢,那麼生產者就必須等待消費者處理完,才能繼續生產資料。同樣的道理,如果消費者的處理能力大於生產者,那麼消費者就必須等待生產者。為了解決這個問題於是引入了生產者和消費者模式。
什麼是生產者消費者模式
生產者消費者模式是通過一個容器來解決生產者和消費者的強耦合問題。生產者和消費者彼此之間不直接通訊,而通過阻塞佇列來進行通訊,所以生產者生產完資料之後不用等待消費者處理,直接扔給阻塞佇列,消費者不找生產者要資料,而是直接從阻塞佇列裡取,阻塞佇列就相當於一個緩衝區,平衡了生產者和消費者的處理能力。
下面來學習一個最基本的生產者消費者模型的例子
# -*- coding:utf-8 -*- __author__ = "Alex Li" import threading,time import queue #設定佇列長度為10,小於10繼續新增資料 q = queue.Queue(maxsize=10) def Producer(name): count = 1 while True: q.put("骨頭%s" % count) print("生產了骨頭",count) count +=1 time.sleep(0.1) defConsumer(name): #while q.qsize()>0: while True: print("[%s] 取到[%s] 並且吃了它..." %(name, q.get())) time.sleep(1) p = threading.Thread(target=Producer,args=("Alex",)) c = threading.Thread(target=Consumer,args=("ChengRonghua",)) c1 = threading.Thread(target=Consumer,args=("王森",)) p.start() c.start() c1.start()
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("李闖")
import time,random import queue,threading q = queue.Queue() def Producer(name): count = 0 while count <20: time.sleep(random.randrange(3)) q.put(count) print('Producer %s has produced %s baozi..' %(name, count)) count +=1 def Consumer(name): count = 0 while count <20: time.sleep(random.randrange(4)) if not q.empty(): data = q.get() print(data) print('\033[32;1mConsumer %s has eat %s baozi...\033[0m' %(name, data)) else: print("-----no baozi anymore----") count +=1 p1 = threading.Thread(target=Producer, args=('A',)) c1 = threading.Thread(target=Consumer, args=('B',)) p1.start() c1.start()