Skip to main content
 首页 » 编程设计

python之在 Python 中退出线程

2025年04月02日15bjzhanghao

我正在尝试编写一个程序来抓取网站并下载它拥有的所有视频。我遇到了一个问题,即即使在完成单个视频的下载后,线程数量也会不断增加。

这里是单个 Worker 对象的代码,它被排队,然后加入。这是我生成线程的唯一代码部分。我不明白的是,如果给定对象,我实现 self.stop() 函数并且 while 循环中断,怎么会有剩余线程。

class Worker(Thread): 
def __init__(self, thread_pool): 
    Thread.__init__(self) 
    self.tasks = thread_pool.tasks 
    self.tasks_info = thread_pool.tasks_info 
    self.daemon = True 
    self._is_running=True 
 
    self.start()         
def stop(self): 
    self._is_running = False 
def run(self): 
    while self._is_running: 
        func, args, kargs = self.tasks.get() 
        try: func(*args, **kargs) 
        except Exception: 
            print("\nError: Threadpool error.") 
            sys.exit(1) 
 
        self.tasks_info['num_tasks_complete'] += 1             
        self.tasks.task_done() 
        self.stop() 

我已经使用线程函数来检查哪些线程处于事件状态,事实证明它确实主要是辅助函数以及其他名为 Thread(SockThread) 和 的对象_MainThread,我不知道如何关闭。

请告知 1. 为什么工作线程没有结束以及 2. 如何摆脱 Thread(SockThread) 以及 _MainThread。

谢谢!

编辑 1

class ThreadPool: 
def __init__(self, name, num_threads, num_tasks): 
 
    self.tasks = Queue(num_threads) 
 
    self.num_threads=num_threads 
    self.tasks_info = { 
        'name': name, 
        'num_tasks': num_tasks, 
        'num_tasks_complete': 0 
    } 
    for _ in range(num_threads): 
        Worker(self) 
    print(threading.active_count) 
 
 
def add_task(self, func, *args, **kwargs): 
    self.tasks.put((func, args, kwargs)) 
def wait_completion(self): 
    print("at the beginning of wait_completion:") 
    print(threading.active_count()) 

请您参考如下方法:

通过查看您的代码,您似乎已经初始化了调用 run() 方法进行处理的线程。在那之后你甚至使用了 start 方法,这不是正确的方法。您的代码应如下所示:

from threading import Event 
class Worker(Thread): 
    def __init__(self, thread_pool): 
       self.tasks = thread_pool.tasks 
       self.tasks_info = thread_pool.tasks_info 
       self.exit = Event() 
       super(Thread,self).__init__() 
 
   def shutdown(self): 
       self.exit.set() 
 
   def run(self): 
       while not self.exit.is_set(): 
          func, args, kargs = self.tasks.get() 
          try:  
              func(*args, **kargs) 
          except Exception: 
              print("\nError: Threadpool error.") 
              # use shutdown method for error 
              self.shutdown() 
              sys.exit(1) 
 
          self.tasks_info['num_tasks_complete'] += 1             
          self.tasks.task_done() 
          self.shutdown()