42. Python Queue 模組

來源:互聯網
上載者:User

標籤:queue

Python提供了Queue模組來專門實現訊息佇列Queue對象

Queue對象實現一個fifo隊列(其他的還有lifo、priority隊列,這裡不再介紹)。

queue只有maxsize一個構造參數,用來指定隊列容量,指定為0的時候代表容量無限。


主要有以下成員函數:

Queue.qsize():返回訊息佇列的當前空間。返回的值不一定可靠。

Queue.empty():判斷訊息佇列是否為空白,返回True或False。同樣不可靠。

Queue.not_empty():判斷訊息佇列是否為非空。同上不可靠。

Queue.full():類似上邊,判斷訊息佇列是否滿。

Queue.put(item, block=True, timeout=None):往訊息佇列中存放訊息。block可以控制是否阻塞,timeout指定阻塞時候的等待時間。如果不阻塞或者逾時,會引起一個full exception。

Queue.put_nowait(item):相當於put(item, False).

Queue.get(block=True, timeout=None):擷取一個訊息,其他同put。

Queue.task_done():接收訊息的線程通過調用這個函數來說明訊息對應的任務已完成。

Queue.join():表示等待,等到隊列為空白,在執行別的操作。

Queue.terminate():表示強制關閉。


例子:

#!/usr/bin/env python# -*- coding:utf-8 -*-from multiprocessing import Queuefrom threading import Threadimport time"""寫一個消費者和生產者,用多線程方式實現,通過類的重寫的方法實現。"""class Proceducer(Thread):    def __init__(self, queue):        super(Proceducer,self).__init__()        self.queue = queue    def run(self):        try:            for i in xrange(1, 10):                print ("put data is {0} to queue".format(i))                self.queue.put(i)        except Exception as e:            print ("put data error")            raise eclass Consumer_even(Thread):    def __init__(self, queue):        super(Consumer_even , self).__init__()        self.queue = queue    def run(self):        try:            while not self.queue.empty():                number = self.queue.get(block=True, timeout=3)                if number % 2 != 0:                    print("get {0} from queue EVEN, thread name is {1}".format(number, self.getName()))                else:                    self.queue.put(number)                time.sleep(1)        except Exception as e:            raise eclass Consumer_odd(Thread):    def __init__(self, queue):        super(Consumer_odd , self).__init__()        self.queue = queue    def run(self):        try:            while not self.queue.empty():                number = self.queue.get(block=True, timeout=3)                if number % 2 == 0:                    print("get {0} from queue ODD".format(number))                else:                    self.queue.put(number)                time.sleep(1)        except Exception as e:            raise edef main():    queue = Queue()    p = Proceducer(queue=queue)    p.start()    p.join()    time.sleep(1)    c1 = Consumer_even(queue=queue)    c2 = Consumer_odd(queue=queue)    c1.start()    c2.start()    c1.join()    c2.join()    print ("All thread terminate!")if __name__ == '__main__':    main()


結果:

put data is 1 to queueput data is 2 to queueput data is 3 to queueput data is 4 to queueput data is 5 to queueput data is 6 to queueput data is 7 to queueput data is 8 to queueput data is 9 to queueget 1 from queue EVEN, thread name is Thread-2get 2 from queue ODDget 3 from queue EVEN, thread name is Thread-2get 4 from queue ODDget 5 from queue EVEN, thread name is Thread-2get 6 from queue ODDget 7 from queue EVEN, thread name is Thread-2get 8 from queue ODDget 9 from queue EVEN, thread name is Thread-2All thread terminate!


42. 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.