日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python实现进程通信_python进程间的通讯实现

發布時間:2025/3/12 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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进程间的通讯实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。