我认为您需要一个带有任务队列的良好线程池。我发现(并使用)了这个非常好的一个(它在 python3 中,但转换为 2.x 应该不会太难):
# http://code.activestate.com/recipes/577187-python-thread-pool/
from queue import Queue
from threading import Thread
class Worker(Thread):
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception as exception: print(exception)
self.tasks.task_done()
class ThreadPool:
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
self.tasks.put((func, args, kargs))
def wait_completion(self):
self.tasks.join()
现在您可以在 iterparse 上运行循环并让线程池为您分配工作。使用它很简单:
def executetask(arg):
print(arg)
workers = threadpool.ThreadPool(4) # 4 is the number of threads
for i in range(100): workers.add_task(executetask, i)
workers.wait_completion() # not needed, only if you need to be certain all work is done before continuing