我正在使用多个线程并行处理目录中的所有文件。一切正常,除了线程似乎保持活动状态,因此进程的线程数会上升,直到达到 1K 左右的线程,然后它会引发thread.error can't start new 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, e: print e
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()
def foo(filename)
pool = ThreadPool(32)
iterable_data = process_file(filename)
for data in iterable_data:
pool.add_task(some_function, data)
pool.wait_completion()
files = os.listdir(directory)
for file in files:
foo(file)