錯(cuò)誤:
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)
學(xué)習(xí)python多線程的使用艺糜,發(fā)現(xiàn)上面的實(shí)例總是在運(yùn)行的拋錯(cuò):
multiprocessing error, 'module' object has no attribute 'print_index'
, 嘗試在百度上搜索答案瘟滨,發(fā)現(xiàn)查出來(lái)的東西都是模凌兩可术幔,有些根本就是掛羊頭系列嫩痰。 辛虧有偉大的stack overflow, 里面提示,錯(cuò)誤原因是進(jìn)程池在方法之前定義。
嘗試將代碼改成下面的格式屠尊, 測(cè)試后發(fā)現(xiàn)再也沒(méi)有錯(cuò)誤拋出。
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)