嗨我有數據存儲在n數量的線程塊。文件的大小是102kb,所以我試圖鎖定共享資源,即文件,然後當我編寫第一個塊時,我釋放了鎖,但是當它來自第二個線程的下一個chink時,而不是文件繼續從它離開的地方它啓動,如果它...當我試圖寫文件的每個塊從線程它被覆蓋
所以102 kb的文件成爲51KB
每一個具有塊這裏是一段代碼51爲兩個線程寫在頂部的組塊。
for th in threads:
th.join()
for th in threads:
lock.acquire()
with open(fileName, 'w+') as fh:
fh.write(th.data)
lock.release()
我甚至使用模式w+
仍代替其附加覆蓋..
更新
def main(url=None, splitBy=2):
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)
# if os.path.exists(fileName):
# if int(sizeInBytes) == os.path.getsize(fileName):
# raise SystemExit("File already exists.")
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)
for i, th in enumerate(threads):
th.join()
lock.acquire()
with open(fileName, 'a') as fh:
fh.write(th.data)
if i == len(threads) - 1:
fh.seek(0, 0)
fh.flush()
lock.release()
更新2
我已經完全刪除了額外的線程清單,只需使用join()
方法做的神奇,但線程如何等待一個塊完成寫它是使用with
等待一個thread.data被寫入,然後下一個可以開始追加?
def main(url=None, splitBy=6):
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)
if os.path.exists(fileName):
if int(sizeInBytes) == os.path.getsize(fileName):
ask = raw_input('[YES]')
if not ask or ask.lower() in ['y', 'yes']:
os.remove(fileName)
else:
raise SystemExit("File already exists.")
start_time = time.time()
print "%s bytes to download." % sizeInBytes
if not sizeInBytes:
print "Size cannot be determined."
return
byteRanges = buildRange(int(sizeInBytes), splitBy)
for idx in range(splitBy):
bufTh = SplitBufferThread(url, byteRanges[idx])
bufTh.daemon = True
bufTh.start()
with open(fileName, 'a+') as fh:
bufTh.join()
fh.write(bufTh.data)
print "--- %s seconds ---" % str(time.time() - start_time)
print "Finished Writing file %s" % fileName
嘗試將模式更改爲「a」而不是「w +」。 「w +」不會追加到文件,而是覆蓋它。請參閱http://stackoverflow.com/questions/16208206/confused-by-python-file-mode-w –
對不起,第一個錯誤是使用'W +',但即使我嘗試用'a'它繼續附加文件,所以我試圖設置'fh.seek(0,0)',但它不起作用,它繼續追加字節 –
等等,你想達到什麼目的?你想要它追加到文件還是覆蓋它? –