我正在编写一个小型多线程http文件下载程序,并希望能够在代码遇到错误时缩小可用线程
错误将特定于在Web服务器不允许更多连接的情况下返回的http错误
例如。如果我设置了5个线程的池,每个线程都试图打开它自己的连接并下载一个文件块。服务器可能只允许2个连接,我相信会返回503错误,我想检测到这个并关闭一个线程,最终将池的大小限制为大概只有服务器允许的2个
我可以自行停止线程吗?
自我。线程 _stop()是否足够?
我是否还需要加入()?
这是我的工作类进行下载,从队列中抓取进行处理,一旦下载就将结果转储到resultQ中,由主线程保存到文件中
在这里,我想检测一个http 503,并从可用池中停止/终止/删除一个线程 - 当然,将失败的块重新添加回队列,以便剩下的线程将处理它
class Downloader(threading.Thread):
def __init__(self, queue, resultQ, file_name):
threading.Thread.__init__(self)
self.workQ = queue
self.resultQ = resultQ
self.file_name = file_name
def run(self):
while True:
block_num, url, start, length = self.workQ.get()
print 'Starting Queue #: %s' % block_num
print start
print length
#Download the file
self.download_file(url, start, length)
#Tell queue that this task is done
print 'Queue #: %s finished' % block_num
self.workQ.task_done()
def download_file(self, url, start, length):
request = urllib2.Request(url, None, headers)
if length == 0:
return None
request.add_header('Range', 'bytes=%d-%d' % (start, start + length))
while 1:
try:
data = urllib2.urlopen(request)
except urllib2.URLError, u:
print "Connection did not start with", u
else:
break
chunk = ''
block_size = 1024
remaining_blocks = length
while remaining_blocks > 0:
if remaining_blocks >= block_size:
fetch_size = block_size
else:
fetch_size = int(remaining_blocks)
try:
data_block = data.read(fetch_size)
if len(data_block) == 0:
print "Connection: [TESTING]: 0 sized block" + \
" fetched."
if len(data_block) != fetch_size:
print "Connection: len(data_block) != length" + \
", but continuing anyway."
self.run()
return
except socket.timeout, s:
print "Connection timed out with", s
self.run()
return
remaining_blocks -= fetch_size
chunk += data_block
resultQ.put([start, chunk])
下面是我初始化线程池的地方,下面我将项目放入队列
# create a thread pool and give them a queue
for i in range(num_threads):
t = Downloader(workQ, resultQ, file_name)
t.setDaemon(True)
t.start()
答案 0 :(得分:1)
你应该使用线程池来控制线程的生命周期:
然后,当一个线程存在时,您可以向主线程(即处理线程池)发送消息,然后更改线程池的大小,并在您将清空的堆栈中推迟新请求或失败请求。
tedelanay对于您为线程提供的守护程序状态绝对正确。没有必要将它们设置为守护进程。
基本上,您可以简化代码,您可以执行以下操作:
import threadpool
def process_tasks():
pool = threadpool.ThreadPool(4)
requests = threadpool.makeRequests(download_file, arguments)
for req in requests:
pool.putRequest(req)
#wait for them to finish (or you could go and do something else)
pool.wait()
if __name__ == '__main__':
process_tasks()
arguments
取决于您的策略。您可以将线程作为参数提供给队列,然后清空队列。或者,您可以在process_tasks中处理队列,在池已满时阻塞,并在线程完成时打开新线程,但队列不为空。这一切都取决于您的需求和下载程序的上下文。
资源:
答案 1 :(得分:1)
我可以自行停止线程吗?
请勿使用self._Thread__stop()
。退出线程的run()
方法就足够了(您可以检查标志或从队列中读取标记值以了解何时退出)。
在这里,我想检测一个http 503,并从可用池中停止/终止/删除一个线程 - 当然,将失败的块重新添加回队列,以便剩下的线程将处理它
您可以通过分离职责来简化代码:
download_file()
不应该尝试在无限循环中重新连接。如果有错误;让我们调用download_file()
的代码在必要时重新提交Semaphore
对象中。在这种情况下,线程数可能与并发连接数不同import concurrent.futures # on Python 2.x: pip install futures
from threading import BoundedSemaphore
def download_file(args):
nconcurrent.acquire(timeout=args['timeout']) # block if too many connections
# ...
nconcurrent.release() #NOTE: don't release it on exception,
# allow the caller to handle it
# you can put it into a dictionary: server -> semaphore instead of the global
nconcurrent = BoundedSemaphore(5) # start with at most 5 concurrent connections
with concurrent.futures.ThreadPoolExecutor(max_workers=NUM_THREADS) as executor:
future_to_args = dict((executor.submit(download_file, args), args)
for args in generate_initial_download_tasks())
while future_to_args:
for future in concurrent.futures.as_completed(dict(**future_to_args)):
args = future_to_args.pop(future)
try:
result = future.result()
except Exception as e:
print('%r generated an exception: %s' % (args, e))
if getattr(e, 'code') != 503:
# don't decrease number of concurrent connections
nconcurrent.release()
# resubmit
args['timeout'] *= 2
future_to_args[executor.submit(download_file, args)] = args
else: # successfully downloaded `args`
print('f%r returned %r' % (args, result))
答案 2 :(得分:0)
Thread对象只是通过从run方法返回来终止线程 - 它不会调用stop。如果将线程设置为守护进程模式,则无需加入,但主线程需要执行此操作。通常,线程使用resultq来报告它正在退出,并且主线程使用该信息来进行连接。这有助于有序地终止您的流程。如果python还在处理多个线程,那么你可以在系统退出期间遇到奇怪的错误,并且最好将其放在一边。