多进程中使用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())
进程池中要使用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())