pipe管道,2个进程通信,允许单项或者双向,multiprocessing.Pipe(duplex=False)为单项,默认双向
示例:
from multiprocessing import Process,Pipe import os def proc1(pipe): pipe.send('hello') print('proc1 rec:',pipe.recv()) def proc2(pipe): print('proc2 rec:',pipe.recv()) pipe.send('hello too') pipe = Pipe() p1 = Process(target=proc1,args=(pipe[0],)) p2 = Process(target=proc2,args=(pipe[1],)) p1.start() p2.start() p1.join() p2.join()
Queue允许多个进程通信
示例:
import os,time import multiprocessing def inputQ(queue): info = str(os.getpid()) + '(put):' + str(time.time()) queue.put(info) def outputQ(queue,lock): info = queue.get() lock.acquire() print(str(os.getpid()) + '(get):' + info) lock.release() rec1 = [] rec2 = [] lock = multiprocessing.Lock() queue = multiprocessing.Queue(3) for i in range(10): process = multiprocessing.Process(target=inputQ,args=(queue,)) process.start() rec1.append(process) for i in range(10): process = multiprocessing.Process(target=outputQ,args=(queue,lock)) process.start() rec2.append(process) for p in rec1: p.join() queue.close() for p in rec2: p.join()