多进程中各个进程间相互隔离,进程间通信需要使用到通道。
多进程中使用Queue实现进程中通信
from multiprocessing import Process,Queue
import time ,random
def f(q, ):
for i in range(10):
n = q.get()
n+=1
q.put( n)
print("计数",n)
print('subpro',id(q))
time.sleep(random.random())
if __name__=='__main__':
q = Queue()
q.put(0)
print('mainpro',id(q))
lst = []
for i in range(3):
p = Process(target=f, args=(q,)) # 必须把q传进去,因为不同进程间内存是不共享的
lst.append(p)
p.start()
for i in lst:
i.join()
print("总数",q.get())
使用进程池时,使用它Queue会出错,需要使用Manager
from multiprocessing import Pool,Manager
import time ,random
def f(q, ):
for i in range(10):
n = q.get()
n+=1
q.put( n)
print("计数",n)
print('subpro',id(q))
time.sleep(random.random())
if __name__=='__main__':
q = Manager().Queue()
q.put(0)
print('mainpro',id(q))
pool = Pool(8)
for x in range(50):
# 添加进程入进程池,注意加"_async",apply为阻塞版本,参数分别为target和args
result = pool.apply_async(f, (q,))
pool.close()
pool.join()
print("总数",q.get())