Python的线程池

2023-02-10 21:02:08 浏览数 (2)

随便发篇文章,测试下百家号的同步功能

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

代码语言:javascript复制
# 线程池的例子
 
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, 爆出的异常往往看不清问题, 需要使用单线程调试之后再去

0 人点赞