0. 生产情况
- 在生产环境一般不使用以下方式
- 在生产环境一般使用以下方式
1. 使用Queue 的方式
import multiprocessing
import time
q = multiprocessing.Queue()
def task(arg):
time.sleep(1)
q.put(arg)
if __name__ == '__main__':
plist = []
for i in range(10):
p = multiprocessing.Process(target=task, args=(i,))
plist.append(p)
for i in plist:
i.start()
while True:
running = 0
for p in plist:
if p.is_alive():
running += 1
if running == 0:
break
for i in range(10):
print(q.get())
2. 使用Manager 的方式
import multiprocessing
import time
m = multiprocessing.Manager()
dic = m.dict()
def task(arg):
time.sleep(1)
dic[arg] = 100
if __name__ == '__main__':
plist = []
for i in range(10):
p = multiprocessing.Process(target=task, args=(i,))
plist.append(p)
for i in plist:
i.start()
while True:
running = 0
for p in plist:
if p.is_alive():
running += 1
if not running:
break
print(dic)