这是我的线程设置。在我的机器上,最大线程数是 2047。
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
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:
"""Pool of threads consuming tasks from a queue"""
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):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
在我模块的其他类中,我从上面调用 ThreadPool 类来创建一个新的线程池。然后我执行操作。这是一个例子:
def upload_images(self):
'''batch uploads images to s3 via multi-threading'''
num_threads = min(500, len(pictures))
pool = ThreadPool(num_threads)
for p in pictures:
pool.add_task(p.get_set_upload_img)
pool.wait_completion()
我遇到的问题是这些线程没有被垃圾收集。
几次运行后,这是我的错误:
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py”,第 495 行,在 start _start_new_thread(self.__bootstrap, ()) thread.error: 无法启动新线程
这意味着我已经达到了 2047 的线程限制。
有任何想法吗?谢谢。