我该如何在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个线程?
请注意,我希望等待所有文件被处理后再继续并处理已处理的文件。
futures
,只需要安装回溯版本即可。 - abarnertmultiprocessing.pool.ThreadPool
来轻松限制线程数,就像这个答案中展示的那样。 - martineau