Ell*_*ial 2 python multithreading python-3.x
最近我做了很多网络或 IO 绑定操作,使用线程有助于大大加快代码速度。我注意到我一直在一遍又一遍地编写这样的代码:
threads = []
for machine, user, data in machine_list:
mythread = threading.Thread(target=get_info, args=(machine, user, data))
mythread.start()
threads.append(mythread)
for mythread in threads:
mythread.join()
Run Code Online (Sandbox Code Playgroud)
这感觉有点重复。它有效,但我怀疑可能有一种更“Pythonic”的方式来编写它。有什么建议么?
您正在寻找的是multiprocessing.pool.ThreadPool,它与 具有相同的语义multiprocessing.pool.Pool,但使用线程而不是进程。
您可以像这样更简洁地执行当前正在执行的操作:
from multiprocessing.pool import ThreadPool
pool = ThreadPool() # optionally pass the number of threads in the pool
res = pool.starmap_async(get_info, machine_list)
res.wait()
Run Code Online (Sandbox Code Playgroud)
这并不完全等同于您的代码,因为ThreadPool创建了固定数量的线程(默认情况下等于可用 CPU 的数量)并在它们之间分配工作,但您仍然可以传递您想要的数量(例如ThreadPool(len(machine_list)))为每个线程创建一个列表中的项目。
然后您还可以创建一个函数来轻松地多次执行此操作:
def run_threads(func, arglist):
ThreadPool(len(arglist)).starmap_async(func, arglist).wait()
Run Code Online (Sandbox Code Playgroud)
注意:.starmap_async()这只是实现这一目标的一种方法。您可以使用多种方法。查看Pool上面链接的文档并选择您喜欢的文档。
| 归档时间: |
|
| 查看次数: |
231 次 |
| 最近记录: |