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

Lecea ·
更新时间:2024-09-21
· 509 次阅读

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

#!/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实现模拟分割大文件及多线程处理的方法Python多线程编程之多线程加锁操作示例Python线程下使用锁的技巧分享



方法 加锁 多线程 线程 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号