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

yipeiwu_com6年前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 多线程不加锁分块读取文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python函数中不定长参数的写法

Python函数中不定长参数的写法

1、不定长参数的写法,用 *变量名 表示 2、不定长参数累加 3、不定长参数,使用**c接受m=23,n=56的值; 传参时,a必写,b、c可以缺省 def fun(a, b,...

JavaScript中的模拟事件和自定义事件实例分析

本文实例讲述了JavaScript中的模拟事件和自定义事件。分享给大家供大家参考,具体如下: 前面介绍了JavaScript中为事件指定处理程序的五种方式和JavaScript的事件对象...

TensorFlow实现简单卷积神经网络

TensorFlow实现简单卷积神经网络

本文使用的数据集是MNIST,主要使用两个卷积层加一个全连接层构建的卷积神经网络。 先载入MNIST数据集(手写数字识别集),并创建默认的Interactive Session(在没有指...

通过mod_python配置运行在Apache上的Django框架

为了配置基于 mod_python 的 Django,首先要安装有可用的 mod_python 模块的 Apache。 这通常意味着应该有一个 LoadModule 指令在 Apache...

python数据结构树和二叉树简介

一、树的定义 树形结构是一类重要的非线性结构。树形结构是结点之间有分支,并具有层次关系的结构。它非常类似于自然界中的树。树的递归定义:树(Tree)是n(n≥0)个结点的有限集T,T为空...