linux一读一写文件多线程,linux学习(35):多线程读取文件(示例代码)

# _*_coding:utf-8_*_

import time, threading, ConfigParser‘‘‘Reader类,继承threading.Thread

@__init__方法初始化

@run方法实现了读文件的操作‘‘‘classReader(threading.Thread):

def __init__(self, file_name, start_pos, end_pos):

super(Reader, self).__init__()

self.file_name=file_name

self.start_pos=start_pos

self.end_pos=end_pos

def run(self):

fd= open(self.file_name, ‘r‘)‘‘‘该if块主要判断分块后的文件块的首位置是不是行首,

是行首的话,不做处理

否则,将文件块的首位置定位到下一行的行首‘‘‘ if self.start_pos != 0:

fd.seek(self.start_pos-1)if fd.read(1) != ‘\n‘:

line=fd.readline()

self.start_pos=fd.tell()

fd.seek(self.start_pos)‘‘‘对该文件块进行处理‘‘‘ while (self.start_pos <=self.end_pos):

line=fd.readline()‘‘‘ dosomthing‘‘‘ self.start_pos =fd.tell()‘‘‘对文件进行分块,文件块的数量和线程数量一致‘‘‘class Partition(object):

def __init__(self, file_name, thread_num):

self.file_name=file_name

self.block_num=thread_num

def part(self):

fd= open(self.file_name, ‘r‘)

fd.seek(0, 2)

pos_list=[]

file_size=fd.tell()

block_size= file_size/self.block_num

start_pos= 0

for i inrange(self.block_num):if i == self.block_num-1:

end_pos= file_size-1pos_list.append((start_pos, end_pos))breakend_pos= start_pos+block_size-1

if end_pos >=file_size:

end_pos= file_size-1

if start_pos >=file_size:breakpos_list.append((start_pos, end_pos))

start_pos= end_pos+1fd.close()returnpos_listif __name__ == ‘__main__‘:‘‘‘读取配置文件‘‘‘ config =ConfigParser.ConfigParser()

config.readfp(open(‘conf.ini‘))

#文件名

file_name= config.get(‘info‘, ‘fileName‘)

#线程数量

thread_num= int(config.get(‘info‘, ‘threadNum‘))

#起始时间

start_time=time.clock()

p=Partition(file_name, thread_num)

t=[]

pos=p.part()

#生成线程for i inrange(thread_num):

t.append(Reader(file_name,*pos[i]))

#开启线程for i inrange(thread_num):

t[i].start()for i inrange(thread_num):

t[i].join()

#结束时间

end_time=time.clock()

print"Cost time is %f" % (end_time - start_time)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值