多線程讀取或寫入,一般會涉及到同步的問題,否則產生的結果是無法預期的。那么在讀取一個文件的時候,我們可以通過加鎖,但讀不像寫操作,會導致文件錯誤,另外鎖操作是有一定的耗時。因此通過文件分塊,可以比較有效的解決多線程讀問題,之前看到有人寫的分塊操作,比較復雜,需要實現建立好線程以及所讀取塊信息,在這里,我提供了一種比較簡便的方法,以供參考。
#!/user/bin/env python#_*_coding:utf-8_*_from threading import Threadimport timefrom processing import Process, Queuefrom multiprocessing import Processfile_path = 't'fd = open(file_path, 'r')def deal(thread_num): i = 1 line_list = [] #20是我的文件行數,正式情況下可以通過wc -l t獲取 while i <= 20/thread_num: line_list.append(fd.readline()) i += 1 return line_listdef todo(thread_name, line_list): # print 'thread_name:',thread_name,'start' for line in line_list: print str(thread_name) + ' counsume:' + line # print 'thread_name:', thread_name, 'end'if __name__ == '__main__': thread_num = 10 thread_list = [] for i in range(thread_num): line_list = deal(thread_num) t = Thread(target=todo, args=[i, line_list]) t.start() thread_list.append(t) for t in thread_list: t.join()
下面是文件格式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
運行的結果如下:

以上這篇Python 多線程不加鎖分塊讀取文件的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答