Python隊列queue模組

來源:互聯網
上載者:User

標籤:sum   基本使用   程式   處理   gif   out   count   規則   div   

 Python中queue模組常用來處理隊列相關問題隊列常用於生產者消費者模型,主要功能為提高效率和程式解耦

 

1. queue模組的基本使用和相關說明

# -*- coding:utf-8 -*-# Author:Wong Du‘‘‘隊列常用於生產者消費者模型,主要功能為提高效率和程式解耦‘‘‘import queue"""執行個體化隊列對象不同規則的三種方法"""q1 = queue.Queue(maxsize=2)   # 先入先出q2 = queue.LifoQueue(maxsize=3)     # 後入先出,Last in first outq3 = queue.PriorityQueue(maxsize=5) # 根據儲存資料的優先順序決定誰先出隊列"""添加資料進隊列中,可添加str、list、tuple等當添加的資料量超過隊列上限的時候,程式會卡住,直到有人從隊列中取出資料若想讓程式不卡住,可以用put_nowait添加資料和配置block或timeout的put參數來讓程式拋出異常,從而進行異常處理或其他動作"""q1.put("caiyun")q1.put( [1, 2, 3, 4, 5] )# q1.put_nowait(2)# q1.put(2, block=False)# q1.put(2, timeout=3)q2.put("caiyun")q2.put( (1, 2, 3, 4, 5) )q3.put(("Wong", 123))q3.put(("Caiyun", 322))q3.put(("dudu", 98))"""擷取隊列中的資料,同理當隊列中沒有資料的時候,程式會卡住,直到有人添加資料在隊列中若想讓程式不卡住,可以用get_nowait添加資料和配置block或timeout的put參數來讓程式拋出異常,從而進行異常處理或其他動作"""print("\033[32;1mQueue Info\033[0m".center(35,‘-‘))print(q1.get())print(q1.get())# q1.get_nowait()# q1.get(block=False)# q1.get(timeout=3)print("\033[33;1mLifoQueue Info\033[0m".center(35,‘-‘))print(q2.get())print(q2.get())print("\033[34;1mPriorityQueue Info\033[0m".center(35,‘-‘))print(q3.get()[0])print(q3.get())# print(q3.get())"""隊列判斷和計數,判斷是否為空白,是否已滿,隊列長度計數"""print(q1.empty())print(q1.full())print(q3.qsize())

 

2. queue模組的簡單應用

 1 # -*- coding:utf-8 -*- 2 # Author:Wong Du 3  4 import time 5 import queue 6 import threading 7  8 q = queue.Queue(maxsize=10) 9 10 def producer(pname):11     count = 112     while True:13         q.put("baozi%s" % count)14         print("\033[31;1m[%s] 生產了 [baozi%s]...\033[0m" %(pname, count))15         count += 116         time.sleep(0.5)17 18 def consumer(cname):19     while True:20         print("\033[33;1m[%s] 收到了 [%s],並把它吃了...\033[0m" %(cname, q.get()))21         time.sleep(2)22 23 p1 = threading.Thread(target=producer, args=("Caiyun", ))24 p1.start()25 26 c1 = threading.Thread(target=consumer, args=("dudu", ))27 c2 = threading.Thread(target=consumer, args=("wong", ))28 c1.start()29 # c2.start()
queue&threading_生產者消費者執行個體

 

Python隊列queue模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.