1. 程式人生 > >python 訊息佇列

python 訊息佇列

複製程式碼
from multiprocessing import Queue, Process

#寫程序
def write(q):
    for i in ["a","b","c","d"]:
         q.put(i)
         print("put {0} to queue".format(i))
#讀程序
def read(q):
    while 1:
        result = q.get()
        print("get {0} from queue".format(result))
#主函式
def main():
# 父程序建立Queue,並傳給各個子程序:
    q = Queue()
    pw = Process(target=write,args=(q,))
    pr = Process(target=read,args=(q,))
    # 啟動子程序pw,寫入:
    pw.start()
    # 啟動子程序pe,讀入:
    pr.start()
   # 等待pw結束:
    pw.join()
  # pr程序裡是死迴圈,無法等待其結束,只能強行終止:
    pr.terminate()

if __name__ == "__main__":
    main()
結果

put a to queue

get a from queue
put b to queue

get b from queue

put c to queue

get c from queue

put d to queue
get d from queue

複製程式碼