python实现进程通信_python进程间的通讯实现
1:進程間通訊的方法:apply_async()非阻塞式通訊? ? ?apply()阻塞式通訊
2:使用Queue實現對Process創建的進程間通訊,
Queue本身是一個消息隊列程序,Queue常用方法:
Queue.qsize():返回當前消息隊列的消息數量
Queue.empty():如果隊列為空,返回true 否則返回false
Queue.full():如果隊列滿了,返回true,否則false
Queue.get():獲取隊列中的一條消息,然后將其從隊列中移除
Queue.put(“xxx”):把內容存放進消息隊列
Queue.get_nowait()相當于Queue.get(False) Queue.put_nowait()相當于Queue.put(False)
例子:
#叫做隊列
from multiprocessing import Queue
from multiprocessing import Process
list = ["lipeng","王五","趙四"]
def write(q):
for temp in list:
print("---%s write to queue"%temp)
q.put(temp)
def read(q):
while 1:
if not q.empty():
value = q.get()
print("--get %s from queue"%value)
else:
print("queue is empty")
break
if __name__ == '__main__':
q = Queue()
pw = Process(target=write,args=(q,))
pr = Process(target=read,args=(q,))
pw.start()#啟動子進程,開始寫
pw.join()#等待pw進程結束
pr.start()
pr.join()
程序輸出:
3: 進程池間通訊方式的實現
Process創建的進程可以使用Queue進行通訊,而進程池Pool創建的進程通訊使用Manager中的Queue來初始化,就不需要再導入Queue模塊。
先看例子:
??from multiprocessing import Pool,Manager
#from multiprocessing import Queue
def write(q):#定義寫入隊列的函數
list = ["111", "222", "555", "666"]
if not q.full():
for temp in list:
print("write %s to Queue"%temp)
q.put(temp)
else:
print("queue is full")
def read(q):
while True:
if not q.empty():
value = q.get()
print("get %s from queue"%value)
else:
print("queue ir empty")
print("所有數據讀寫完畢")
break
if __name__ == '__main__':
#創建隊列
q = Manager().Queue()#使用Manager中的Queue來初始化
#創建寫進程
po = Pool()
#使用阻塞模式創建進程,這樣就不需要在read中使用死循環,可以讓write執行完成后再用read進程
po.apply(write,(q,))
po.apply(read,(q,))
po.close()
po.join()
程序輸出如下:
很累很累,但我還是要解釋一下這個代碼:
首先導入mutiprocessing模塊下的Process類Manager類,定義write函數實現把數據寫入隊列,定義read函數實現對隊列中的消息進行讀取。
在write函數中以隊列q(使用Manager中的Queue來初始化),判斷隊列是否滿,遍歷要寫入的數據使用put方法寫入。否則輸出隊列已滿
在read函數中以隊列q(使用Manager中的Queue來初始化),判斷隊列時候是空,使用get方法和遍歷隊列獲取每一個隊列中的值并輸出。
在程序入口處先創建隊列,聲明進程池,在選擇使用阻塞式模式創建進程,最后關閉子進程,結束父進程。
總結
以上是生活随笔為你收集整理的python实现进程通信_python进程间的通讯实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言深度解剖 pdf,c语言深度解剖
- 下一篇: qt5python gui cookbo