# -*- coding: utf-8 -*-
importos,
time
import
threading
rlock
=threading
.rlock
()curposition =0
class
reader
(threading
.thread
):def
__init__
(self
,res
):self
.res
=res
super
(reader
,self
).__init__
()def
run(
self
):global
curposition
fstream
=open
(self
.res
.filename
,'r'
)while
true
:#鎖定共享資源
rlock
.acquire
()startposition
=curposition
curposition
=endposition =(
startposition
+self
.res
.blocksize)if
(startposition
+self
.res
.blocksize
)<
self
.res
.filesize
else
self
.res
.filesize
#釋放共享資源
rlock
.release
()if
startposition
==self
.res
.filesize
:break
elif
startposition !=0
:fstream
.seek
(startposition
)fstream
.readline
()pos
=fstream
.tell
()while
pos
<
endposition
:line
=fstream
.readline
()#處理line
#print(line.strip())
pos
=fstream
.tell
()fstream
.close
()class
resource
(object
):def
__init__
(self
,filename
):self
.filename
=filename
#分塊大小
self
.blocksize
=100000000
self
.getfilesize
()#計算檔案大小
defgetfilesize
(self
):fstream
=open
(self
.filename
,'r'
)fstream
.seek(0
,os.seek_end
)self
.filesize
=fstream
.tell
()fstream
.close
()if
__name__
=='__main__'
:starttime
=time
.clock
()#執行緒數
threadnum =4
#檔案filename
='ipdata.txt'
;res
=resource
(filename
)threads =
#初始化執行緒
fori
inrange
(threadnum
):rdr
=reader
(res
)threads.(
rdr)
#開始執行緒
fori
inrange
(threadnum
):threads[i
].start
()#結束執行緒
fori
inrange
(threadnum
):threads[i
].join
()print
(time
.clock()-
starttime
)
Python 多執行緒分塊讀取檔案
什麼也不說,直接上 絕對看的懂 coding utf 8 import time,threading,configparser reader類,繼承threading.thread init 方法初始化 run方法實現了讀檔案的操作 class reader threading.thread def...
python多執行緒分塊讀取檔案
coding utf 8 import time,threading,configparser reader類,繼承threading.thread init 方法初始化 run方法實現了讀檔案的操作 cl程式設計客棧ass reader threading.thread def init self...
Python 多執行緒不加鎖分塊讀取檔案
多執行緒讀取或寫入,一般會涉及到同步的問題,否則產生的結果是無法預期的。那麼在讀取乙個檔案的時候,我們可以通過加鎖,但讀不像寫操作,會導致檔案錯誤,另外鎖操作是有一定的耗時。因此通過檔案分塊,可以比較有效的解決多執行緒讀問題,之前看到有人寫的分塊操作,比較複雜,需要實現建立好執行緒以及所讀取塊資訊,...