Python 的 ThreadPool


Author: yifei / Created: Nov. 9, 2017, 3:30 a.m. / Modified: Nov. 9, 2017, 11:31 a.m. / Edit

multiporcessing.Pool.map(fn, iterable) only accepts marshalable  

# 线程池的例子
 
from multiprocessing.dummy import Pool as ThreadPool  # python2
from multiprocessing.pool import ThreadPool # python3
 
def square_number(n):
    return n ** 2
 
# function to be mapped over
def calculate_parallel(numbers, threads=2):
    pool = ThreadPool(threads)
    results = pool.map(square_number, numbers)
    pool.close()  # NOTE close before join
    pool.join()
    return results
 
if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    squared_numbers = calculate_parallel(numbers, 4)
    for n in squared_numbers:
        print(n)

  使用pool的一个陷阱是不太好debug, 爆出的异常往往看不清问题, 需要使用单线程调试之后再去


评论区