测试代码如下:
# -*- coding: utf-8 -*- import multiprocessing import time def func(msg): print('msg: ', msg) time.sleep(1) print('----') pool = multiprocessing.Pool(processes=4) for i in range(10): msg = 'hello world %d' % i pool.apply_async(func, (msg, )) pool.close() pool.join()
上面的代码运行将产生如下错误信息:
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its .
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
从错误信息可以看出进程池相关代码应该放在if __name__ == '__main__'下面,代码修改如下:
# -*- coding: utf-8 -*- import multiprocessing import time def func(msg): print('msg: ', msg) time.sleep(1) print('----') if __name__ == '__main__': pool = multiprocessing.Pool(processes=4) for i in range(10): msg = 'hello world %d' % i pool.apply_async(func, (msg, )) pool.close() pool.join()