进程这间其实是不能通信的,之所以能通信其实利用了一个中间件的方法,类似于pickle 以 下是信息传递:
from multiprocessing import Process,Queue
import queue
def f(qq):
qq.put([42,None,'hello'])
if __name__=="__main__":
q = Queue()
p = Process(target=f,args=(q,))
p.start()
print(q.get())
p.join()
线程通信比较更简单一点,因为线程共享内存:
import threading
import queue
def f():
q.put([42,None,'hello'])
if __name__=="__main__":
p = threading.Thread(target=f,)
q = queue.Queue()
p.start()
print(q.get())
p.join()
也可以用管道方法:
from multiprocessing import Process,Pipe
def f(conn):
conn.send([45, None, 'nihao'])
conn.close()
if __name__ == '__main__':
parent_conn,child_conn = Pipe()
p = Process(target=f,args=(child_conn,))
p.start()
print(parent_conn.recv())
p.join()
管道通信也可以子进程和父进程通信
from multiprocessing import Process,Pipe
def f(conn):
conn.send([45, None, 'nihao'])
print('from parent:',conn.recv())#收到父子进程信号
conn.close()
if __name__ == '__main__':
parent_conn,child_conn = Pipe()
p = Process(target=f,args=(child_conn,))
p.start()
print(parent_conn.recv())
parent_conn.send([0,2,3])#发货给子进程
p.join()
以下是进程间共享数据:用的上Mabager
from multiprocessing import Process, Manager
import os
def f(d, l):
d[os.getpid()] = os.getpid()
l.append(os.getpid())
print(l)
if __name__ == '__main__':
with Manager() as manager:
d = manager.dict()
l = manager.list(range(5))
p_list = []
for i in range(10):
p = Process(target=f, args=(d, l))
p.start()
p_list.append(p)
for res in p_list:
res.join()
print(d)
print(l)