我觉得不是p定义的位置,如果报错是:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
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.
那这么修改就可以啦~
import multiprocessing
import time
import os
import random
def worker(msg):
start_time = time.time()
print("开始执行进程 %d ----- %s" % (msg, os.getpid()))
time.sleep(random.random() * 2)
stop_time = time.time()
print(msg, '耗费时间是 %0.2f' % (stop_time - start_time))
def main():
multiprocessing.freeze_support()
pool = multiprocessing.Pool()
cpus = multiprocessing.cpu_count()
[pool.apply_async(worker, args=(i, )) for i in range(0, cpus)]
pool.close()
pool.join()
if __name__ == '__main__':
main()