【发布时间】: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