Advertisement

python进程池multiprocessing.Pool运行错误:The freeze_support() line can be omitted if the program is not g

阅读量:

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 ’下面,代码修改如下:

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()

全部评论 (0)

还没有任何评论哟~