欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-02-19 15:21:36|栏目: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 多线程不加锁分块读取文件

上一篇:Python中的defaultdict与__missing__()使用介绍

栏    目:Python代码

下一篇:对python中xlsx,csv以及json文件的相互转化方法详解

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

本文地址:http://www.codeinn.net/misctech/66174.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有