本文來源於python 3.5版本的官方文檔
multiprocessing模塊為進程間通信提供了兩種方法:
1.進程隊列queue
The Queue class is a near clone of queue.Queue。
Queues are thread and process safe。
使用進程隊列,可以在兩個進程間傳遞消息。其用法跟queue.Queue類似。
使用方法:
from multiprocessing import Process,Queue
def func(q):
q.put([42,None,"hello"]) #把一個列表放入一個隊列中
if __name__=="__main__":
q1=Queue() #定義一個隊列
p1=Process(target=func,args=(q1,)) #實例化一個進程
p1.start() #啟動進程
print(q1.get()) #從隊列中取出一個項目,並打印
p1.join() #阻塞進程
返回值:
[42, None, 'hello']
在進程間通信可以使用python中所有的數據類型,但這種方式並不是真正意義上的進程間的通信。
2.管道pipe
The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way).
The two connection objects returned by Pipe() represent the two ends of the pipe. Each connection object has send() and recv() methods (among others).
Note that data in a pipe may become corrupted if two processes (or threads) try to read from or write to the same end of the pipe at the same time.
Of course there is no risk of corruption from processes using different ends of the pipe at the same time.
pipe()返回兩個連接對象代表pipe的兩端。每個連接對象都有send()方法和recv()方法。
但是如果兩個進程或線程對象同時讀取或寫入管道兩端的數據時,管道中的數據有可能會損壞。
當進程使用的是管道兩端的不同的數據則不會有數據損壞的風險。
使用方法:
from multiprocessing import Process,Pipe
def func(conn):
conn.send([42,None,"hello"]) #連接發出信息
conn.close() #關閉連接
if __name__=="__main__":
parent_conn,child_conn=Pipe() #定義一個管道
p1=Process(target=func,args=(child_conn,)) #實例化一個進程
p1.start() #啟動進程
print(parent_conn.recv()) #連接接收信息並打印
p1.join() #阻塞進程
返回結果:
[42, None, 'hello']
本文來源於python 3.5版本的官方文檔