求助,请教个和Pool有关的定义函数的问题

ldahual 2015-12-28 09:07:40
请教一下:
主程序 if __name__ == '__main__': 中可以def定义函数吗?

代码如下:
'fun test'

from multiprocessing.pool import Pool
import time

if __name__ == '__main__':

def ppfun(id):
print('proc(%d) start' %id)
time.sleep(2)
print('proc(%d) end' %id)
return str(id) + 'done'

p = Pool(processes = 3)
results = []
for i in range(4):
results.append(p.apply_async(ppfun, args = (i,)))
p.close()
p.join()
for res in results:
print(type(res))
print(res.get())
print('process(es) all done')

print('FIN')

运行起来会报异常:
AtrributeError: Can't get atrribute 'ppfun' on <module '__mp_main__' from 'E:\\...\\....\\funtest.py'>

并且程序卡死
如果把ppfun的定义放在 if __name__ == '__main__':外面运行就OK。
尝试不涉及Pool的另外的代码,在 if __name__ == '__main__':中def定义函数运行正常。
请教下这是怎么回事?另外'__mp_main__'表示什么?
python版本3.4
...全文
58 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

37,719

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧