python 處理序間通訊Queue

來源:互聯網
上載者:User

標籤:code   class   range   執行個體   apply   修改   __name__   技術   狀態   

  • Queue的使用

    Queue.qsize()    #返回當前隊列包含的訊息數量

    Queue.empty()   #如果隊列為空白,返回True,反之False 
    Queue.full()     #如果隊列滿了,返回True,反之False

    Queue.get([block[, timeout]])  #擷取隊列中的一條訊息,然後將其從列隊中移除,block預設值為True,沒取到會阻塞

                   #如果block值為False,訊息列隊如果為空白,則會立刻拋出"Queue.Empty"異常

    Queue.get_nowait()      #相當Queue.get(False)

    Queue.put(item,[block[, timeout]])   #將item訊息寫入隊列,block預設值為True,

                      #訊息列隊如果已經沒有空間可寫入,此時程式將被阻塞(停在寫入狀態),直到從訊息列隊騰出空間為止

                      #如果block值為False,訊息列隊如果沒有空間可寫入,則會立刻拋出"Queue.Full"異常

    Queue.put_nowait(item)    #相當Queue.put(item, False)

  • 執行個體

    Process

    

from multiprocessing import Process, Queueimport os, time, random# 寫資料進程執行的代碼:def write(q):    for value in [‘A‘, ‘B‘, ‘C‘]:        print(‘Put %s to queue...‘ % value)        q.put(value)        time.sleep(random.random())# 讀資料進程執行的代碼:def read(q):    while True:        if not q.empty():            value = q.get(True)            print(‘Get %s from queue.‘ % value)            time.sleep(random.random())        else:            breakif __name__==‘__main__‘:    # 父進程建立Queue,並傳給各個子進程:    q = Queue()    pw = Process(target=write, args=(q,))    pr = Process(target=read, args=(q,))    # 啟動子進程pw,寫入:    pw.start()    # 等待pw結束:    pw.join()    # 啟動子進程pr,讀取:    pr.start()    pr.join()    # pr進程裡是死迴圈,無法等待其結束,只能強行終止:    print (‘所有資料都寫入並且讀完‘)

  Pool

#coding=utf-8#修改import中的Queue為Managerfrom multiprocessing import Manager,Poolimport os,time,randomdef reader(q):    print("reader啟動(%s),父進程為(%s)"%(os.getpid(),os.getppid()))    for i in range(q.qsize()):        print("reader從Queue擷取到訊息:%s"%q.get(True))def writer(q):    print("writer啟動(%s),父進程為(%s)"%(os.getpid(),os.getppid()))    for i in "dongGe":        q.put(i)if __name__=="__main__":    print("(%s) start"%os.getpid())    q=Manager().Queue() #使用Manager中的Queue來初始化    po=Pool()    #使用阻塞模式建立進程,這樣就不需要在reader中使用死迴圈了,可以讓writer完全執行完成後,再用reader去讀取    po.apply(writer,(q,))    po.apply(reader,(q,))    po.close()    po.join()    print("(%s) End"%os.getpid())

 

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.