<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:

def downloader(self):
        '''the download thread'''
        while self.tiles_pending() > 0:
            time.sleep(self.tile_delay)

            keys = sorted(self._download_pending.keys())

            # work out which one to download next, choosing by request_time
            tile_info = self._download_pending[keys[0]]
            for key in keys:
                if self._download_pending[key].request_time > tile_info.request_time:
                    tile_info = self._download_pending[key]

            url = tile_info.url(self.service)
            path = self.tile_to_path(tile_info)
            key = tile_info.key()

            try:
                if self.debug:
                    print("Downloading %s [%u left]" % (url, len(keys)))
                req = url_request(url)
                if url.find('google') != -1:
                    req.add_header('Referer', 'https://maps.google.com/')
                resp = url_open(req)
                headers = resp.info()
            except url_error as e:
                #print('Error loading %s' % url)
                if not key in self._tile_cache:
                    self._tile_cache[key] = self._unavailable
                self._download_pending.pop(key)
                if self.debug:
                    print("Failed %s: %s" % (url, str(e)))
                continue
            if 'content-type' not in headers or headers['content-type'].find('image') == -1:
                if not key in self._tile_cache:
                    self._tile_cache[key] = self._unavailable
                self._download_pending.pop(key)
                if self.debug:
                    print("non-image response %s" % url)
                continue
            else:
                img = resp.read()

            # see if its a blank/unavailable tile
            md5 = hashlib.md5(img).hexdigest()
            if md5 in BLANK_TILES:
                if self.debug:
                    print("blank tile %s" % url)
                    if not key in self._tile_cache:
                        self._tile_cache[key] = self._unavailable
                self._download_pending.pop(key)
                continue

            mp_util.mkdir_p(os.path.dirname(path))
            h = open(path+'.tmp','wb')
            h.write(img)
            h.close()
            try:
                os.unlink(path)
            except Exception:
                pass
            os.rename(path+'.tmp', path)
            self._download_pending.pop(key)
        self._download_thread = None