Python线程未被垃圾回收。

5

这是我的线程设置。在我的计算机上,最大线程数为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_new_thread(self.__bootstrap, ())时出错。thread.error: 无法启动新线程。
这意味着我已经达到了2047个线程的限制。
有什么想法吗?谢谢。
2个回答

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()

我来试试这段代码。我以为 tasks.task_done() 做的是类似于退出并垃圾回收线程的操作! - Lucas Ou-Yang
哦,@LucasOu-Yang task_done() 应该像你所做的那样在异常处理程序之外(我会纠正它)。但是你仍然需要退出 run 方法。任务队列对处理线程一无所知。 - Henry Gomersall

1
def run(self):
    while True:
        func, args, kargs = self.tasks.get()
        try:
            func(*args, **kargs)
        except Exception, e:
            print e
        self.tasks.task_done()

看起来像是一个无限循环,这可能是原因吗?所有线程都是活着的,所以它们不能被垃圾回收。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接