首页 > 解决方案 > 无法停止 python 线程

问题描述

我编写了类似于以下条带程序的 GUI python 应用程序,

启动从 URL 列表下载数据的线程,URL 列表有时非常大,因此用户可能决定取消下载并在其他时间恢复,但是当我停止线程时,我无法重新启动或恢复它

 downloader.start()
  File "C:\Python38\lib\threading.py", line 848, in start
    raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once

我的问题是如何为此类下载任务编写安全启动/停止/恢复任务线程

代码


def dataDataDowload():

  for i in range(0,len(urlList)):
    
    if not os.path.isdir(ProjectPath+urlList[i]):       
       os.makedirs(ProjectPath+urlList[i].name)
    urllib.request.urlretrieve(urlList[i], ProjectPath+urlList[i].name+'data.dat')
  

class Download(threading.Thread):
    def __init__(self,arg):
        #super(Download, self).__init__()
        super().__init__()
        self.paused = True  # Start out paused.
        self.state      = threading.Condition()
        self.stop_event = threading.Event()

            
    def run(self):
        while True:
            if self.isStopped():
                return
            dataDataDowload()

    def stop(self):
        self.stop_event.set() 

        
    def isStopped(self):
        return self.stop_event.isSet()
        
    def pause(self):
        with  self.state:
              self.paused = True  # Block self.

    def resume(self):
        with self.state:
             self.paused = False
                 
    
downloader= Download() 

    

标签: python-3.xmultithreadingclassthread-safety

解决方案


请求任务的最佳解决方案是在单独的线程或进程中使用异步 io。在与主线程相当的管道连接的单独线程中并处理每个可用任务(在这种情况下为新链接请求)在工作线程中异步 io 处理下载请求的获取并在完成作业后通知主线程


推荐阅读