python-3.x - 无法停止 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()
解决方案
请求任务的最佳解决方案是在单独的线程或进程中使用异步 io。在与主线程相当的管道连接的单独线程中并处理每个可用任务(在这种情况下为新链接请求)在工作线程中异步 io 处理下载请求的获取并在完成作业后通知主线程
推荐阅读
- react-native - 重新加载时反应本机加载旧版本
- ios - IOS 版 Google Cardboard VR 应用出现黑屏
- git - Git合并两个完全不同的分支
- jquery - jQuery,跟踪谷歌分析的电话点击
- hibernate - Spring Boot 读取用户上传的 csv 文件
- python - 我试图在多维列表中找到一个特定的值。但是当我试图找到那个特定的值时,我的函数将什么也不返回
- amazon-web-services - 多个账户的 AWS AssumeRole 账户 ID 问题
- php - 进行 php mailer 是否有任何其他要求
- http - HTTP 日志文件中的 x-forwarded-for 和 client_ip 之间的区别?
- php - mime_content_type():只能处理字符串或流参数