Python 多线程不加锁分块读取文件

多线程读取或写入,一般会涉及到同步的问题,否则产生的结果是无法预期的。那么在读取一个文件的时候,我们可以通过加锁,但读不像写操作,会导致文件错误,另外锁操作是有一定的耗时。因此通过文件分块,可以比较有效的解决多线程读问题,之前看到有人写的分块操作,比较复杂,需要实现建立好线程以及所读取块信息,在这里,我提供了一种比较简便的方法,以供参考。


#!/user/bin/env python
#_*_coding:utf-8_*_
from threading import Thread
import time
from processing import Process, Queue

from multiprocessing import Process

file_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_list


def 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 多线程不加锁分块读取文件_第1张图片

你可能感兴趣的:(Python)