当前位置: 移动技术网 > IT编程>脚本编程>Python > Python 多线程不加锁分块读取文件的方法

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

2019年06月13日  | 移动技术网IT编程  | 我要评论

长沙化妆学校,ailete277,驾驶证扣分

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

#!/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 多线程不加锁分块读取文件

以上这篇python 多线程不加锁分块读取文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网