【问题标题】:can't stop the python thread无法停止 python 线程
【发布时间】:2021-06-28 02:03:09
【问题描述】:

我编写了类似于以下条带程序的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.x multithreading class thread-safety


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2014-05-29
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2014-08-31
      相关资源
      最近更新 更多