Python多重处理:在函数内调用pool.map

Mic*_*ael 2 python windows function multiprocessing python-3.x

我正在尝试使用该mutltiprocessing程序包在一个函数中使用多个CPU。当我在功能之外运行玩具示例时,它可以在四分之一秒内运行而不会出现问题(请参见下文)。

from multiprocessing import Pool
import time

start = time.clock()

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(processes=7) as pool:     
        result = pool.map(f, range(1000))



print(time.clock() - start)
Run Code Online (Sandbox Code Playgroud)

但是,当我将相同的代码改编为一个函数(请参见下文)时,它会打印True以指示__name__ == '__main__',但它将永远运行并且永远不会返回结果。我在Windows 7上运行Python 3.3。

from multiprocessing import Pool
import time

start = time.clock()

def f(x):
    return x*x

def testfunc(r):
    if __name__ == '__main__':
        print(True)
        with Pool(processes=7) as pool:     
            result = pool.map(f, range(r))

    return result

result = testfunc(1000)
print(time.clock() - start)
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 5

if __name__ == '__main__'在错误的地方使用。

from multiprocessing import Pool
import time

start = time.clock()

def f(x):
    return x*x

def testfunc(r):
    print(True)
    with Pool(processes=7) as pool:     
        result = pool.map(f, range(r))
    return result

if __name__ == '__main__':
    result = testfunc(1000)
    print(time.clock() - start)
Run Code Online (Sandbox Code Playgroud)

根据multiprocessing - Programming guidelines

安全导入主模块

确保可以通过新的Python解释器安全地导入主模块,而不会引起意外的副作用(例如,启动新进程)。

...应该使用if __name__ =='__main__'来保护程序的“入口点”: