1. 程式人生 > >Python 程序間通訊 Queue

Python 程序間通訊 Queue

Queue是多程序的安全佇列,可以使用Queue實現多程序之間的資料傳遞。

Queue的一些常用方法:

  • Queue.qsize():返回當前佇列包含的訊息數量;
  • Queue.empty():如果佇列為空,返回True,反之False ;
  • Queue.full():如果佇列滿了,返回True,反之False;
  • Queue.get():獲取佇列中的一條訊息,然後將其從列隊中移除,可傳參超時時長。
  • Queue.get_nowait():相當Queue.get(False),取不到值時觸發異常:Empty;
  • Queue.put():將一個值新增進數列,可傳參超時時長。
  • Queue.put_nowait():相當於Queue.get(False),當佇列滿了時報錯:Full。

from multiprocessing import Process,Queue
import time

def write(q):
    for i in ['A','B','C','D','E']:
        print('Put %s to queue' % i)
        q.put(i)
        time.sleep(0.5)

def read(q):
    while True:
        v = q.get(True)
        print('get %s from queue' % v)

if __name__ == '__main__':
    q = Queue()
    pw = Process(target=write,args=(q,))
    pr = Process(target=read,args=(q,))
    print('write process = ',pw)
    print('read  process = ',pr)
    pw.start()
    pr.start()
    pr.join()
    pr.terminate()
    pw.terminate()