Python线程没有被垃圾回收

Luc*_*ang 5 python multithreading python-multithreading

这是我的线程设置。在我的机器上,最大线程数为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()
Run Code Online (Sandbox Code Playgroud)

在模块的其他类中,我从上面调用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()
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是这些线程没有被垃圾回收。

经过几次运行,这是我的错误:

文件“ /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py”,第495行,位于开始_start_new_thread(self .__ bootstrap,())thread.error中:无法启动新线程

这意味着我已经达到2047的线程限制。

有任何想法吗?谢谢。

Hen*_*all 4

你的工作线程永远不会从 中返回run,所以你的线程永远不会结束。

也许您的方法类似于以下内容run

def run(self):
    while True:
        try:
            func, args, kargs = self.tasks.get()
        except Queue.Empty:
            break

        try:
            func(*args, **kargs)
        except Exception, e:
            print e

        self.tasks.task_done()
Run Code Online (Sandbox Code Playgroud)