在同一时间使用多个进程同时运行,可能导致反馈数据顺序是乱的,为保证得到理想的数据顺序,就需要添加一把锁以控制数据的顺序输出。
from multiprocessing import Manager,Pipe,Process,os, Lock
def t(lock,d,l):
lock.acquire() # 加锁
try:
d[os.getpid()] = os.getpid()
l.append(os.getpid())
finally:
lock.release() # 释放
if __name__ =='__main__':
# parent_cnn, child_cnn = Pipe() # 管道生成两个实例
lock = Lock()
with Manager() as manager:
d = manager.dict()
l = manager.list(range(10)) # 声明一个[0,1,2,3....,9]的列表
p_list = []
for i in range(5):
p = Process(target=t,args=(lock, d,l))
# p.daemon = True
p.start()
p_list.append(p)
for j in p_list:
j.join()
print d # {11160: 11160, 11161: 11161, 11162: 11162, 11163: 11163, 11164: 11164}
print l # [0, 1
# 进程池
from multiprocessing import Process, Pool, Lock
import os, time
def f(i):
time.sleep(1)
print('hello',os.getpid())
def Bar(*args):
print('程序完成之后,主进程进行回调...',os.getpid())
if __name__ == '__main__':
pool = Pool(5) # 创建进程池
print(os.getpid())
for i in range(10):
# pool.apply(func=f, args=(i,)) # 串行执行
pool.apply_async(func=f, args=(i,), callback=Bar)
# 并行执行 callback 为回调函数,指的是执行完func之后才会执行的方法函数
# pool.apply_async(func=f, args=(i,))
pool.close()
pool.join()
print('end')