初入Python 进程池的坑 module' object has no attribute

错误:

from multiprocessing import  Pool
import time

thread_pool = Pool(processes=10)

def print_index(index):
    time.sleep(1)
    print index

def main(limit):
    thread_pool.apply_async(print_index, [limit])
    thread_pool.map(print_index, range(limit))
    thread_pool.close()
    thread_pool.join()


if __name__ == '__main__':
    main(10)

学习python多线程的使用,发现上面的实例总是在运行的抛错:
multiprocessing error, 'module' object has no attribute 'print_index', 尝试在百度上搜索答案,发现查出来的东西都是模凌两可,有些根本就是挂羊头系列。 辛亏有伟大的stack overflow, 里面提示,错误原因是进程池在方法之前定义。

尝试将代码改成下面的格式, 测试后发现再也没有错误抛出。

from multiprocessing import  Pool
import time



def print_index(index):
    time.sleep(1)
    print index
    
thread_pool = Pool(processes=10)
def main(limit):
    thread_pool.apply_async(print_index, [limit])
    thread_pool.map(print_index, range(limit))
    thread_pool.close()
    thread_pool.join()


if __name__ == '__main__':
    main(10)

链接: https://stackoverflow.com/questions/2782961/yet-another-confusion-with-multiprocessing-error-module-object-has-no-attribu

你可能感兴趣的:(初入Python 进程池的坑 module' object has no attribute)