multiprocessing error “AttributeError: Can't get attribute 'testfuncxx' on <module '__main__”

北慕城南 提交于 2021-01-29 11:10:09

问题


#!/usr/bin/env python3.5
import multiprocessing, time

def testfuncxx(num):
    time.sleep(num)
    print(num


pool = multiprocessing.Pool(processes=3)

)

for i in range(10):
    #testfuncxx(i)
    #print(i, '=======')
    pool.apply_async(testfuncxx, args=(i,))

pool.close()
pool.join()

回答1:


Since I can only test on Windows, the code works when I enclose the code in a if __name__ == '__main__' entry-point protection. More details here. In general, including this protection is recommended in the multiprocessing guidelines.

Note: The code was run as a script test.py. To run the code in IPython or Jupyter notebook, you may import it like import test.

test.py:

import multiprocessing, time

def testfuncxx(num):
    time.sleep(num)    
    print(num)

def apply_async_callback():  
    pool = multiprocessing.Pool(processes=3) 
    for i in range(10):  
        pool.apply_async(testfuncxx, args=(i,))
    pool.close()
    pool.join()  


if __name__=='__main__':    
    apply_async_callback()

#Output:
0
1
2
3
4
5
6
7
8
9


来源:https://stackoverflow.com/questions/57105439/multiprocessing-error-attributeerror-cant-get-attribute-testfuncxx-on-modu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!