deffunc(q,name):#以參數的方式將對列物件以參數型式導入子進程 q.put('My Process_name is %s and put the data to the id %d queue'%(name,id(q))) if __name__ == "__main__": q = Queue() #於主進程創建隊列物件 process_list=[] print("main queue id: %d"%id(q)) for i inrange(3): proc = Process(target=func,args=(q,'Process-%d'%i)) process_list.append(proc) proc.start() print(q.get()) #往管道中取數據 print(q.get()) print(q.get()) for each_process in process_list: each_process.join()
Queue()參數可填入管道的長度
Queue(3)表示創建能存三筆資料的管道物件
創建的Queue物件可放置任意數據類型
通過Queue.get()取數據
先put的先取出,後put的後取出
要是Queue為空的情況下,還執意get的話,會堵塞到有數據可取出為止
可使用Queue.get_nowait()方法,要是堵塞了會直接報錯
其結果如下
1 2 3 4
main queue id: 52342000 My Process_name is Process-1 and put the data to the id 64566512 queue My Process_name is Process-0 and put the data to the id 43398512 queue My Process_name is Process-2 and put the data to the id 61551856 queue
from multiprocessing import Process,Pipe import os
deffunc(conn): conn.send("Hi I'm your subprocess. My ID is %d"%os.getpid()) print("ID %d receive main_process message: "%os.getpid(),conn.recv()) conn.close() if __name__ == "__main__": main_conn , sub_conn = Pipe() #使用Pipe()函數同時建立主進程及自進程兩個通信的物件 processlist=[] for i inrange(2): proc = Process(target=func,args=(sub_conn,)) processlist.append(proc) proc.start() print("I'm mainprocess, I receive my sub_process message: ",main_conn.recv()) main_conn.send("Remember I'm your Master") for each_process in processlist: each_process.join()
其結果如下
1 2 3 4
I'm mainprocess, I receive my sub_process message: Hi I'm your subprocess. My ID is 8424 ID 8424 receive main_process message: Remember I'm your Master I'm mainprocess, I receive my sub_process message: Hi I'm your subprocess. My ID is 13468 ID 13468 receive main_process message: Remember I'm your Master