python线程池
版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc
起因: python的进程池,大家都用过,但是线程池很多人估计都用错了
错误的库
估计不少人都用的是这个库
https://pypi.python.org/pypi/threadpool/1.3.2
但是这个库其实是有问题的,程序有时候会异常退出。其实作者明确指出,这个库已经废弃了
This module is OBSOLETE and is only provided on PyPI to support old projects that still use it. Please DO NOT USE IT FOR NEW PROJECTS! Use modern alternatives like the multiprocessing module in the standard library or even an asynchroneous approach with asyncio.
简单翻译下:
这个模块已经废弃了,请不要再在新项目中使用它
推荐使用标准库的线程池
from multiprocessing.dummy import Pool as ThreadPool
def square(x):
print x * x
worker_count = 10
pool = ThreadPool(worker_count)
task_list = range(10)
pool.map(square, task_list)
pool.close()
pool.join()
运行结果
╰─$ python test_threadpool.py
01
9
4
16
25
36
49
64
81
Support for the API of the multiprocessing package using threads
线程池的API与进程池的API几乎完全一致,见参考资料1