多进程启动方法"spawn"、"fork"的选择
官方指导
实践
使用官方的例子: python版本为3.9.6
根据官方的说法,3.8开始默认就是spawn了,而不是fork。
from multiprocessing import Process, Lock def f(l, i): l.acquire() try: print('hello world', i) finally: l.release() if __name__ == '__main__': lock = Lock() for num in range(10): Process(target=f, args=(lock, num)).start()
官方的例子竟然报错了(因为官方例子太早了,在出官方例子的时候还没有迭代到python3.8, 即使用的是fork)。
所以消除报错有2个解决方案:
1. 使用fork启动
2. spawn的话需要对进程join
解决方案1
from multiprocessing import Process, Lock, set_start_method def f(l, i): l.acquire() try: print('hello world', i) except Exception as e: print(e, 'vth') finally: l.release() if __name__ == '__main__': # set_start_method('fork') lock = Lock() p_s = [] for num in range(10): p = Process(target=f, args=(lock, num)) p.start() p_s.append(p) for p in p_s: p.join()
解决方案2
from multiprocessing import Process, Lock, set_start_method def f(l, i): l.acquire() try: print('hello world', i) except Exception as e: print(e, 'vth') finally: l.release() if __name__ == '__main__': set_start_method('fork') lock = Lock() p_s = [] for num in range(10): p = Process(target=f, args=(lock, num)) p.start() # p_s.append(p) # for p in p_s: # p.join()