Python 多线程不加锁分块读取文件的方法
多线程读取或写入一般会涉及到同步的问题否则产生的结果是无法预期的。那么在读取一个文件的时候我们可以通过加锁但读不像写操作会导致文件错误另外锁操作是有一定的耗时。因此通过文件分块可以比较有效的解决多线程读问题之前看到有人写的分块操作比较复杂需要实现建立好线程以及所读取块信息在这里我提供了一种比较简便的方法以供参考。123456789101112131415161718192021222324252627282930313233343536373839404142#!/user/bin/env python#_*_coding:utf-8_*_fromthreadingimportThreadimporttimefromprocessingimportProcess, QueuefrommultiprocessingimportProcessfile_pathtfdopen(file_path,r)defdeal(thread_num):i1line_list[]#20是我的文件行数正式情况下可以通过wc -l t获取whilei 20/thread_num:line_list.append(fd.readline())i1returnline_listdeftodo(thread_name, line_list):# print thread_name:,thread_name,startforlineinline_list:printstr(thread_name) counsume:line# print thread_name:, thread_name, endif__name____main__:thread_num10thread_list[]foriinrange(thread_num):line_listdeal(thread_num)tThread(targettodo, args[i, line_list])t.start()thread_list.append(t)fortinthread_list:t.join()下面是文件格式1234567891011121314151617181920运行的结果如下以上这篇Python 多线程不加锁分块读取文件的方法就是小编分享给大家的全部内容了