Python 如何在线程完成字节范围后立即将文件块写入磁盘

Python 如何在线程完成字节范围后立即将文件块写入磁盘,python,multithreading,urllib,http-range,Python,Multithreading,Urllib,Http Range,从这一点继续: 我发现在一个列表中保存字节的数据可能很昂贵,并且可能会降低系统性能,因此我认为最好在该线程的范围完成后立即将数据写入磁盘,因此区块整理的其余部分应该写入队列中下一个线程整理的范围区块 def main(url=None, splitBy=6): start_time = time.time() if not url: print "Please Enter some url to begin download." return

从这一点继续:

我发现在一个列表中保存字节的数据可能很昂贵,并且可能会降低系统性能,因此我认为最好在该线程的范围完成后立即将数据写入磁盘,因此区块整理的其余部分应该写入队列中下一个线程整理的范围区块

def main(url=None, splitBy=6):
    start_time = time.time()
    if not url:
        print "Please Enter some url to begin download."
        return

    fileName = url.split('/')[-1]
    sizeInBytes = requests.head(url, headers={'Accept-Encoding': 'identity'}).headers.get('content-length', None)
    print "%s bytes to download." % sizeInBytes
    if not sizeInBytes:
        print "Size cannot be determined."
        return
    threads = []
    lock = threading.Lock()

    byteRanges = buildRange(int(sizeInBytes), splitBy)
    for idx in range(splitBy):
        bufTh = SplitBufferThread(url, byteRanges[idx])
        bufTh.daemon = True
        bufTh.start()
        threads.append(bufTh)

    print "--- %s seconds ---" % str(time.time() - start_time)

    with open(fileName, 'w+') as fh:
        for t in threads:
            t.join()
            fh.write(t.data)
        fh.flush()

    print "Finished Writing file %s" % fileName

if __name__ == '__main__':
    main(url)

那么,如何在线程完成字节范围后立即将文件块写入磁盘?

这里的问题是什么?@JamieCockburn:如何在线程完成字节范围后立即将文件块写入磁盘?每个线程都需要一个打开的文件句柄和文件中的偏移量来写入下载的数据。您可能还需要提供一个锁,以防止文件被多个线程同时写入。如何根据当前逻辑锁定等待的线程?