【发布时间】:2013-08-21 00:53:16
【问题描述】:
如何限制 Python 中的并发线程数?
例如,我有一个包含许多文件的目录,我想处理所有文件,但一次只能并行处理 4 个。
这是我目前所拥有的:
def process_file(fname):
# open file and do something
def process_file_thread(queue, fname):
queue.put(process_file(fname))
def process_all_files(d):
files=glob.glob(d + '/*')
q=Queue.Queue()
for fname in files:
t=threading.Thread(target=process_file_thread, args=(q, fname))
t.start()
q.join()
def main():
process_all_files('.')
# Do something after all files have been processed
如何修改代码以便一次只运行 4 个线程?
请注意,我想等待所有文件都处理完毕,然后继续处理已处理的文件。
【问题讨论】:
-
你试过multiprocessPools吗?在 Python 3 上,您还可以使用 futures。
-
你也可以在 Python 2 中使用
futures,你只需要安装 backport。 -
concurrent.futures 确实是最好的方法
-
您可以使用
multiprocessing.pool.ThreadPool轻松限制线程数,如this answer 中的另一个问题所示。
标签: python multithreading